Skip to content

Instantly share code, notes, and snippets.

@willmurphyscode
Created March 13, 2017 10:28
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 willmurphyscode/df9592a15faf6e188a51877850270963 to your computer and use it in GitHub Desktop.
Save willmurphyscode/df9592a15faf6e188a51877850270963 to your computer and use it in GitHub Desktop.
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