Skip to content

Instantly share code, notes, and snippets.

@kachick
Last active December 23, 2015 14:59
Show Gist options
  • Save kachick/6651983 to your computer and use it in GitHub Desktop.
Save kachick/6651983 to your computer and use it in GitHub Desktop.
superclass(ancestor)のメソッドを再定義している時に、どの定義を使うか指定する
$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"
$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