2

我有一个模型,它引用和实例变量是另一个类的实例。我想将缺少的方法委托给该变量,如下所示:

  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
4

2 回答 2

1

请检查您的@other_class_instance。从你写的我想这个实例也有 response_to?和 method_missing 被覆盖并产生您看到的错误消息。如果您在 @other_class_instance 不覆盖标准方法查找的情况下编写“干净”测试,那么一切都会按您的预期工作。

是的,洛根是完全正确的,在你的情况下,只需将调用传递给@other_class_instanse.send!

于 2014-04-18T21:15:47.917 回答
1

为什么要检查respond_to?是否仍要发生错误?只需使用send,就会发生 NoMethodError。请参阅http://codepad.org/AaQYWjtQ - 这是您所说的正常堆栈跟踪的意思吗?

于 2014-04-18T19:53:21.263 回答