Skip to content

Instantly share code, notes, and snippets.

@XrXr XrXr/affect-all-instances.rb Secret
Last active Jul 25, 2019

Embed
What would you like to do?
Demo script to show that the effect of tracing an instance method is global across all instances of that class.
class Foo
def hello(arg = nil)
puts "dale sent me"
end
end
one = Foo.new
two = Foo.new
one.hello
two.hello
# so this is a weird one, the call event happens right after
# entering a method instead of before a call happens, as one
# might intuitively expect
trace = TracePoint.new(:call) { |tp| puts "intercepted! arg=#{tp.binding.local_variable_get(:arg)}" }
trace.enable(target: Foo.instance_method(:hello)) do
one.hello(:first)
two.hello(:second)
end
[tmp]# ruby -v affect-all-instances.rb
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-linux]
dale sent me
dale sent me
intercepted! arg=first
dale sent me
intercepted! arg=second
dale sent me
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.