Last active
June 25, 2019 09:47
-
-
Save ridiculous/783cf3686c51341ba32f to your computer and use it in GitHub Desktop.
Method tracking. Could be used to unobtrusively track method calls
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 | |
def track(*args) | |
@__tracking ||= [] | |
args.each { |arg| @__tracking << arg unless tracking?(arg) } | |
end | |
def track!(*args) | |
track(*args) | |
start_tracking! | |
end | |
def track_all! | |
track!(*(methods + instance_methods)) | |
end | |
def tracking?(method_name) | |
@__tracking.include?(method_name) | |
end | |
def start_tracking! | |
mod = Module.new | |
@__tracking.each do |method_name| | |
mod.module_eval <<-RUBY, __FILE__, __LINE__ | |
def #{method_name}(*args, &block) | |
msg = "called #{method_name} " | |
msg << "with " << args.join(', ') << " " if args.any? | |
msg << "from #{__FILE__}:#{__LINE__}" | |
puts msg | |
super | |
end | |
RUBY | |
end | |
mod.module_eval <<-RUBY, __FILE__, __LINE__ | |
def self.prepended(base) | |
base.extend(self) | |
end | |
RUBY | |
prepend(mod) | |
end | |
end | |
class Dog | |
extend ObjectTracker | |
def woof! | |
'woofing so hard right now' | |
end | |
def go(name) | |
"Going to #{name}'s house" | |
end | |
end | |
Dog.track_all! | |
Dog | |
#=> inspect called from (irb):27 | |
Dog.new.go('Ryan') | |
#=> called new from (irb):27 | |
#=> called go with Ryan from (irb):27 | |
#=> Going to Ryan's house |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment