如果实例是通过 ActiveRecord 关联定义的,则忽略自定义 method_missing

发布于 2024-10-16 01:30:25 字数 470 浏览 2 评论 0原文

我提交的内容可能处于各种状态,并编写了一个 method_missing 覆盖,它允许我通过像

submission.draft?
submission.published?

这样的调用来检查它们的状态,效果非常好。


由于各种可能不太好的原因,我还拥有一个名为 Packlet 的模型,该模型属于会议并属于提交。然而,我惊讶地发现它

packlet.submission.draft?

返回了 NoMethodError。另一方面,如果我将 #draft? 方法硬编码到 Submission 中,则上述方法调用有效。


即使实例是通过 ActiveRecord 关联定义的,如何才能识别出我的 method_missing 方法?

I have submissions that might be in various states and wrote a method_missing override that allows me to check their state with calls like

submission.draft?
submission.published?

This works wonderfully.


I also, for various reasons that might not be so great, have a model called Packlet that belongs_to a meeting and belongs_to a submission. However, I was surprised to find that

packlet.submission.draft?

returns a NoMethodError. On the other hand, if I hard-code a #draft? method into Submission, the above method call works.


How do I get my method_missing methods to be recognized even when the instance is defined via an ActiveRecord association?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

镜花水月 2024-10-23 01:30:25

你添加了草稿吗?你的respond_to方法?该对象的方法?我的猜测是,问题可能会出现在那里。当您输入以下内容时会发生什么:

submission.respond_to?(:draft?)

要解决此问题,实际上要编写一个respond_to?像这样的方法:

def respond_to?(method, include_priv = false) #:nodoc:
  case method.to_sym
  when :draft?, :published?
    true
  else
    super(method, include_priv)
  end
end

我的建议是在不使用 method_missing 的情况下实现这个方法,所以通过进行一些像这样的元编程:

class Submission
  [:draft, :published].each do |status|
    define_method "#{status}?" do
      status == "#{status}?"
    end
  end
end

Have you added the draft? method to your respond_to? method for that object? My guess would be that the issue might arise there. What happens when you type:

submission.respond_to?(:draft?)

To fix this, actually write a respond_to? method like this:

def respond_to?(method, include_priv = false) #:nodoc:
  case method.to_sym
  when :draft?, :published?
    true
  else
    super(method, include_priv)
  end
end

My recommendation would be to implement this without using method_missing instead though, so by doing some meta-programming like this:

class Submission
  [:draft, :published].each do |status|
    define_method "#{status}?" do
      status == "#{status}?"
    end
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文