14.5. The Case of the Missing Method

In most programming languages, calling a method that doesn't exist is a one-way ticket to Exception-land. As should be clear by now, Ruby isn't like most programming languages, so there are a couple of hook methods defined to allow you to have last-ditch access to any wayward method calls. The first method in question is called method_missing(symbol, *args), where symbol is the name of the nonexistent method and args is the list of all the arguments in the call. (To be fair, the method_missing idea comes from Smalltalk, which uses a similar method called doesNotUnderstand. Python also has a similar feature, although in practice Python programmers tend not to use it quite as often.)

There are all kinds of interesting things you can do with method_missing, if you are so inclined. The default implementation is just to throw an exception. An obvious thing to do in method_missing is to use some kind of different logging of that exception, but still throw the exception anyway.

On a more functional level, method_missing can be used to implement a simple proxy as follows:

def method_missing(symbol, *args)
  proxy.send(symbol, *args) if proxy.respond_to?(symbol)
  super
end

All this does is redirect the missing method to an object designated as the proxy. The if clause just ensures that the proxy will only get the method if it actually defines the method.

But it's possible to get much more inventive. I really love the example given for method_missing in ...

Get Professional Ruby on Rails™ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.