custom method_missing ignored if instance is defined via an ActiveRecord association

374 views Asked by At

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?

1

There are 1 answers

1
Pan Thomakos On BEST ANSWER

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