Created
May 31, 2015 01:15
-
-
Save kenmazaika/cd80b0379655d39690d8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ObjectTracker | |
module ClassMethods | |
def track_method(method_name) | |
alias_method :"#{method_name}_without_tracking", method_name | |
define_method :"#{method_name}_with_tracking" do |*splat| | |
params = self.class.instance_method(:"#{method_name}_without_tracking").parameters.collect(&:last) | |
self.send(:"#{method_name}_without_tracking", *splat) # do method first | |
self.track_event!(method_name, Hash[*(params.zip(splat).flatten)]) # then track | |
end | |
alias_method method_name, :"#{method_name}_with_tracking" | |
end | |
end | |
end | |
class Dog | |
include ObjectTracker | |
extend ObjectTracker::ClassMethods | |
attr_accessor :name | |
def initialize(name) | |
@name = name | |
end | |
def go(yolo, swag) | |
puts "Going to #{yolo}'s house #{swag}" | |
end | |
def track_event!(method_name, attrs) | |
# attrs is a hash of the arguments that the method was called with | |
# convert them | |
attrs = attrs.keys.collect {|k| [k, attrs[k]].join("=") } | |
# Do whatever you want with the instance variables, or the arguments the method was called with | |
puts "<#{self.class}.#{method_name} name=#{@name} #{attrs.join(" ")}>" | |
end | |
end | |
Dog.track_method(:go) | |
Dog.new("Sparky").go('Ryan', "Swag") | |
puts | |
jon = Dog.new("Jon") | |
jon.go("Bark", "Woof") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment