Skip to content

Instantly share code, notes, and snippets.

@alebian
Last active April 12, 2017 15:48
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 alebian/b8a2350803ee3471b4ebd5b05abb2fca to your computer and use it in GitHub Desktop.
Save alebian/b8a2350803ee3471b4ebd5b05abb2fca to your computer and use it in GitHub Desktop.
class Spy
def self.spy(klass, method)
define_counter(klass, method)
klass.singleton_class.class_eval do
define_method(method) do |*args, &block|
instance_variable_set("@spied_#{method}_counter", instance_variable_get("@spied_#{method}_counter") + 1)
super(*args, &block)
end
end
end
def self.define_counter(klass, method)
klass.instance_variable_set("@spied_#{method}_counter".to_sym, 0)
klass.singleton_class.class_eval do
define_method("spied_#{method}_counter".to_sym) do
instance_variable_get("@spied_#{method}_counter")
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment