Created
January 23, 2014 07:59
-
-
Save johnskopis/8574679 to your computer and use it in GitHub Desktop.
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 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