在运行时的方法中,有没有办法知道该方法是否已被调用super
在子类中?例如。
module SuperDetector
def via_super?
# what goes here?
end
end
class Foo
include SuperDetector
def bar
via_super? ? 'super!' : 'nothing special'
end
end
class Fu < Foo
def bar
super
end
end
Foo.new.bar # => "nothing special"
Fu.new.bar # => "super!"
我怎么能写via_super?
,或者,如果有必要,via_super?(:bar)
?
可能有更好的方法,但总体思路是Object#instance_of?
仅限于当前类,而不是层次结构:
module SuperDetector
def self.included(clazz)
clazz.send(:define_method, :via_super?) do
!self.instance_of?(clazz)
end
end
end
class Foo
include SuperDetector
def bar
via_super? ? 'super!' : 'nothing special'
end
end
class Fu < Foo
def bar
super
end
end
Foo.new.bar # => "nothing special"
Fu.new.bar # => "super!"
However, note that this doesn't require explicit
super
in the child. If the child has no such method and the parent's one is used,
via_super?
will still return
true
. I don't think there is a way to catch only the
super
case other than inspecting the stack trace or the code itself.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)