CSC/ECE 517 Fall 2011/ch3 3i ws
Introduction
Considerations
Drawbacks
All else being equal, method_missing is less efficient at runtime than normally defined methods. Besides the fact that the missing_method will need additional checks to determine the next course of action, method_missing is always the last place the ruby interpreter looks. [1]
Method_missing can make the code more difficult for humans to follow. It is also does not work well with autocomplete and other features of IDE's or editors.
All of these things should be considered when deciding whether to rely on method_missing.
Relationship to respond_to?
Ruby objects also have a method called respond_to? which checks to see that a given message corresponds to a method of the class. By default, it will only look for explicitly defined methods. If none are found, it has no mechanism to check whether it is handled by method_missing. This issue is important to consider if the class or its children ever need the respond_to? method. It is good practice to always override the respond_to? method when using method_missing in a class that might be subclassed. In the stub below, we add a respond_to to the Roman Numerals class.
class Roman def respond_to? if method_sym.to_s =~ ... // regex to see if it's a valid roman numeral true else super end end end
Similar functionality in other languages
The method_missing class is defined in the Object class, so it is inherited by all objects. It raises a NoMethodError by default.
There are no similar methods in statically typed languages like Java or C++. Python does not have an equivalent method either, though it can be simulated using the __getattr__ method [2] Firefox's JavaScript implementation now supports a similar __noSuchMethod__ object. [3] method, but it is not a JavaScript standard.