Created
May 21, 2017 23:59
-
-
Save anthonylebrun/c80f232d7089ccb643193e9a671d44c7 to your computer and use it in GitHub Desktop.
A function that allows spying on ruby objects
This file contains hidden or 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
class Watchable | |
def do_something(foo, bar) | |
puts "Did something with #{foo} and #{bar}" | |
end | |
end | |
module Spycraft | |
def self.spy(instance) | |
instance.instance_eval do | |
public_methods(false).each do |meth| | |
old_method = method(meth) | |
define_singleton_method meth do |*args| | |
puts "[DEBUG] Called #{meth} with arguments: (#{args.map(&:inspect).join(', ')})" | |
old_method.call(*args) | |
end | |
end | |
end | |
end | |
end | |
watchable = Watchable.new | |
Spycraft.spy(watchable) | |
watchable.do_something("FOO", "BAR") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment