Skip to content

Instantly share code, notes, and snippets.

@theterminalguy
Forked from kenmazaika/alias_method.rb
Created December 22, 2017 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theterminalguy/18fa600f05faae2048747e59044da5a0 to your computer and use it in GitHub Desktop.
Save theterminalguy/18fa600f05faae2048747e59044da5a0 to your computer and use it in GitHub Desktop.
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