Skip to content

Instantly share code, notes, and snippets.

@anthonylebrun
Created May 21, 2017 23:59
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 anthonylebrun/c80f232d7089ccb643193e9a671d44c7 to your computer and use it in GitHub Desktop.
Save anthonylebrun/c80f232d7089ccb643193e9a671d44c7 to your computer and use it in GitHub Desktop.
A function that allows spying on ruby objects
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