gpt4 book ai didi

ruby-on-rails - ruby respond_to_missing?叫 super 还是不叫?

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:06 24 4
gpt4 key购买 nike

查看 Rails 代码库有时会出现 respond_to_missing?调用 super 有时不调用。是否存在不应从 respond_to_missing 调用 super 的情况?

最佳答案

这取决于类的实现和您希望 #respond_to_missing? 的行为。查看 ActiveSupport::TimeWithZone,它是 Time 的代理包装器。它试图模仿它,让您误以为它是 Time 的一个实例。例如,TimeWithZone#is_a? 在经过 Time 时会响应 true

# Say we're a Time to thwart type checking.
def is_a?(klass)
klass == ::Time || super
end
alias_method :kind_of?, :is_a?

respond_to_missing? 应该捕获将被 method_missing 捕获的情况,因此您必须查看这两种方法。 TimeWithZone#method_missing 将缺失的方法委托(delegate)给 Time 而不是 super

def method_missing(sym, *args, &block)
wrap_with_time_zone time.__send__(sym, *args, &block)
rescue NoMethodError => e
raise e, e.message.sub(time.inspect, inspect), e.backtrace
end

因此,将 respond_to_missing? 也委托(delegate)给 Time 是有道理的。

# Ensure proxy class responds to all methods that underlying time instance
# responds to.
def respond_to_missing?(sym, include_priv)
return false if sym.to_sym == :acts_like_date?
time.respond_to?(sym, include_priv)
end

关于ruby-on-rails - ruby respond_to_missing?叫 super 还是不叫?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45465607/

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