Last active
December 23, 2015 14:59
-
-
Save kachick/6651983 to your computer and use it in GitHub Desktop.
superclass(ancestor)のメソッドを再定義している時に、どの定義を使うか指定する
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
$VERBOSE = true | |
class Super | |
def a | |
"super_a" | |
end | |
def b | |
"super_b" + c | |
end | |
def c | |
"super_c" | |
end | |
end | |
class Sub < Super | |
def a | |
self.class.superclass.instance_method(:b).bind(self).call | |
end | |
def b | |
"sub_b" + c | |
end | |
def c | |
"sub_c" | |
end | |
end | |
#=> "super_bsub_c" |
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
$VERBOSE = true | |
module MethodDefinedModuleAddressable | |
def method(name, mod=nil) | |
if mod | |
mod.instance_method(name).bind self | |
else | |
super name | |
end | |
end | |
end | |
class Object | |
include MethodDefinedModuleAddressable | |
end | |
class Super | |
def a | |
"super_a" | |
end | |
def b | |
"super_b" + c | |
end | |
def c | |
"super_c" | |
end | |
end | |
class Sub < Super | |
def a | |
method(:b, Super).call | |
end | |
def a2 | |
method(:b).call | |
end | |
def b | |
"sub_b" + c | |
end | |
def c | |
"sub_c" | |
end | |
end | |
p Sub.new.a #=> "super_bsub_c" | |
p Sub.new.a2 #=> "sub_bsub_c" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment