Skip to content

Instantly share code, notes, and snippets.

@johnskopis
Created January 23, 2014 07:59
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 johnskopis/8574679 to your computer and use it in GitHub Desktop.
Save johnskopis/8574679 to your computer and use it in GitHub Desktop.
class Foo
def baz
'The original class is noisy'
raise 'Noise'
end
end
module MonkeyPatch
def self.extended(obj)
[ :baz ].each do |meth|
obj.define_singleton_method("#{meth}!") do
obj.class.instance_method(meth).bind(obj).call
end
instance_eval do
define_method meth do
begin
send "#{meth}!"
rescue => e
warn "monkey patch handled #{e} in #{meth}"
end
end
end
end
end
end
begin
ff = Foo.new
p ff.baz
rescue => e
p "caller handled #{e}"
end
f = Foo.new
f.extend MonkeyPatch
p f.baz
ff = Foo.new
p ff.baz # Oh noez!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment