Last active
April 24, 2024 19:57
-
-
Save itarato/80e29ab7373a760305608a94abb15295 to your computer and use it in GitHub Desktop.
Poorman's Ruby Spy
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 Foo | |
def bar(val, key:) | |
puts("BAR #{val} #{key}") | |
end | |
end | |
def spy_on(object, method) | |
did_call = false | |
aliased = "#{method}_spied".to_sym | |
object.class.instance_eval do | |
alias_method aliased, method | |
end | |
object.instance_eval do | |
self.class.define_method(method) do |*args, **kwargs| | |
did_call = true | |
send(aliased, *args, **kwargs) | |
end | |
end | |
yield | |
raise unless did_call | |
end | |
foo = Foo.new | |
spy_on(foo, :bar) do | |
foo.bar(42, key: "real") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment