O'Reilly logo

Metaprogramming Ruby 2 by Paolo Perrotta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

method_missing

Where you listen to spooky stories about Ghost Methods and dynamic proxies and you try a second way to remove duplicated code.

With Ruby, there’s no compiler to enforce method calls. This means you can call a method that doesn’t exist. For example:

methods/method_missing.rb
 
class​ Lawyer; ​end
 
nick = Lawyer.new
 
nick.talk_simple
<= 
NoMethodError: undefined method `talk_simple' for #<Lawyer:0x007f801aa81938>

Do you remember how method lookup works? When you call talk_simple, Ruby goes into nick’s class and browses its instance methods. If it can’t find talk_simple there, it searches up the ancestors chain into Object and eventually into BasicObject.

Because Ruby can’t find talk_simple anywhere, it admits defeat by calling ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required