0

Whenever I talk to Rubyists I hear great things about method_added and method_missing. However, I got recently chided for using both in a project. The argument was that another library (such as rspec, for example) could overload the methods too and put the program in a strange state depending on which version of method_missing got called first.

I'm curious to know how often this happens. Is it really that dangerous to overload method_missing? Does anyone have real-world examples of woe arising from method_missing conflicts?

1 Answer 1

4

One thing to keep in mind that if you (re)define method_missing on a class, you're replacing any previous implementations of this method (from a Gem for example). You can avoid this by creating a new class that inherits from the class you want to extend with method_missing.

However, this is normally not an issue as most Gems have their own classes.

The other thing to keep in mind is to always call super at the end of method_missing to not break the method invocation chain.

def method_missing(m, *args, &block)
  # your code...

  super
end

Maybe this Graphic of the Ruby Method Lookup Flow is also helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.