我有一个模型,它引用和实例变量是另一个类的实例。我想将缺少的方法委托给该变量,如下所示:
def method_missing(method_name, *args, &block)
if @other_class_instance.respond_to?(method_name)
@other_class_instance.send(method_name, *args)
else
super
end
end
但是,在 @other_class_instance 没有响应的情况下,我希望应用程序终止并像正常的 NoMethodError 一样获得完整的回溯。相反,我只收到一行错误消息,例如:
#<NoMethodError: undefined method `my_method' for #<MyClass:0x00000009022fc0>>
我在几个地方读到过,如果 super 不存在,它会弄乱 Ruby 的方法查找。
我错过了什么,所以如果other_class_instance
不响应该方法,它会表现得好像没有method_missing
创建任何方法?
更新
Logan 的回答在 OtherInstance 类也没有method_missing
定义的情况下解决了这个问题。如果确实如此(比如 Rails 模型),您可以执行以下操作:
begin
raise NoMethodError.new method_name
rescue => e
logger.fatal e
logger.fatal e.backtrace
super
end