Last active
August 29, 2015 14:26
-
-
Save equivalent/621e63629185283ffb5b to your computer and use it in GitHub Desktop.
Rebind module method example
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
# run me with ruby >= 2.0 | |
module A | |
def x(arg) | |
"hi #{arg}" | |
end | |
end | |
module B | |
def x(arg) | |
"cooool #{arg}" | |
end | |
end | |
class Awesome | |
attr_accessor :woodoo | |
def be_awesome(name) | |
woodoo.bind(self).call(name) | |
end | |
end | |
a = Awesome.new | |
a.woodoo = A.instance_method(:x) | |
result = a.be_awesome("tomas") | |
puts result | |
a.woodoo = B.instance_method(:x) | |
result = a.be_awesome("tomas") | |
puts result | |
# If you run this with Ruby >= 2.0 | |
# You should see this on your screen: | |
# | |
# hi tomas | |
# cooool tomas | |
# | |
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
# you cannot bind class instance methods | |
# unless they are from the same ancestory chain: | |
# | |
class A | |
def x(arg) | |
"hi #{arg}" | |
end | |
end | |
class Awesome < A | |
attr_accessor :woodoo | |
def be_awesome(name) | |
woodoo.bind(self).call(name) | |
end | |
def x(arg) | |
"hi #{arg}" | |
end | |
end | |
a = Awesome.new | |
a.woodoo = A.instance_method(:x) | |
a.be_awesome("tomas") | |
# => "hi tomas" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
more info