#method_missing is a very useful part of the ruby language. However, there’s one common mistake that developers make when using it. They forget to add a call to #super.
Let’s take a look:
$ irb
>> class Foo
>> end
=> nil
>> f=Foo.new
=> #
>> f.i_do_not_exist
NoMethodError: undefined method `i_do_not_exist' for #
from (irb):5
>> class Foo
>> def method_missing(symbol,*args)
>> if (symbol.to_s === "i_do_not_exist")
>> puts "Yes, actually you do"
>> end
>> end
>> end
=> nil
>> f.i_do_not_exist
Yes, actually you do
=> nil
>> f.i_exist
=> nil
Unfortunately, we no longer get the error when we try to invoke a method which does not exist. When we add an invocation to super, it’ll behave as expected:
>> class Foo
def method_missing(symbol,*args)
if (symbol.to_s === "i_do_not_exist")
puts "Yes, actually you do"
else
super
end
end
end
>> >> >> >> ?> >> >> >> => nil
>> f.i_exist
NoMethodError: undefined method `i_exist' for #
from (irb):31:in `method_missing'
from (irb):35
>> f.i_do_not_exist
Yes, actually you do
=> nil
>>
You’re still missing something. This is better:
def method_missing(meth, *args, &block)
if (meth == :i_do_not_exist)
puts “Yes, actually you do”
else
super(meth, *args, &block)
end
end
You are most definitely correct. Oops! Thanks for catching that.