This file contains 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 Stubbable | |
def stub(name, block) | |
send(:define_singleton_method, name, block) | |
end | |
end | |
class Class | |
def stub(name, block) | |
send(:define_singleton_method, name, block) | |
end | |
def stub_any_instance(name, block) | |
ObjectSpace.each_object(self) do |instance| | |
begin | |
instance.send(:define_singleton_method, name, block) | |
rescue RuntimeError | |
next # don't set method on frozen strings | |
rescue TypeError | |
next # don't set method on numeric types | |
end | |
end | |
end | |
end | |
stubby = Stubbable.new | |
begin | |
stubby.foo | |
rescue NoMethodError => e | |
puts e.inspect | |
end | |
foo_block = proc { puts 'foo' } | |
stubby.stub(:foo, foo_block ) | |
stubby.foo | |
Stubbable.stub('foo', proc { puts 'class foo' }) | |
Stubbable.foo | |
puts 'Now let\'s put a method on every object' | |
a = '' | |
b = {} | |
c = [] | |
d = Object.new | |
e = '' | |
objs = [a, b, c, d, e] | |
forty_two = proc { puts '42' } | |
Object.stub_any_instance('print42', forty_two) | |
objs.each { |obj| obj.print42 } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment