gpt4 book ai didi

ruby - 当前的 Ruby 方法是通过 super 调用的吗?

转载 作者:数据小太阳 更新时间:2023-10-29 07:10:38 26 4
gpt4 key购买 nike

在运行时的方法中,有没有办法知道该方法是否已通过子类中的 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!"


但是,请注意,这不需要在 child 中显式 super 。如果 child 没有这样的方法而使用了 parent 的方法, via_super? 仍将返回 true。我认为除了检查堆栈跟踪或代码本身之外,没有办法只捕获 super 情况。

关于ruby - 当前的 Ruby 方法是通过 super 调用的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34736850/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com