我有一个引用实例变量的模型,该实例变量是另一个类的实例。我想将缺少的方法委托(delegate)给该变量,如下所示:
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
最佳答案
如果您希望错误发生,为什么要检查 respond_to?
?只要使用 send
就会发生 NoMethodError 。请参阅http://codepad.org/AaQYWjtQ - 这就是你所说的正常堆栈跟踪吗?
关于ruby-on-rails - Rails 方法缺失 - 如何获取 'else' 案例的回溯?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23159905/