Created
February 18, 2014 23:47
-
-
Save cho45/9083068 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
#!ruby | |
class Foo | |
def hello | |
puts "Hello" | |
end | |
end | |
def localize_method(klass, method, &block) | |
unbound = klass.instance_method(method) | |
klass.send(:define_method, method) do | |
block.call(unbound.bind(self)) | |
end | |
lambda { | |
klass.send(:define_method, method, unbound) | |
} | |
end | |
foo = Foo.new | |
foo.hello | |
#=> Hello | |
puts "====" | |
release = localize_method(Foo, :hello) do |orig| | |
puts "before hello" | |
orig.call | |
puts "after hello" | |
end | |
foo.hello | |
#=> before hello | |
# Hello | |
# after hello | |
release.call | |
puts "====" | |
foo.hello | |
#=> Hello |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment