Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use `method_missing`

In the code below, method roar is not defined in class Lion, but still can be called using method_missing.

class Lion
  def method_missing(name, *args)
    puts "Lion will #{name}: #{args[0]}"
  end
end

lion = Lion.new
lion.roar("ROAR!!!") # => Lion will roar: ROAR!!!

In which situations and how should I use this method_missing? And is it safe to use?

like image 752
tokhi Avatar asked Dec 07 '12 09:12

tokhi


1 Answers

It's entirely safe to use provided you use it in expected ways and don't get carried away. Not everything you can do is worth doing, after all.

The advantage of method_missing is you can respond to all kinds of things in unique ways.

The disadvantage is you don't advertise your capabilities. Other objects that expect you to respond_to? something will not get confirmation and might treat your custom object in ways you don't intend.

For building Domain Specific Languages and providing very loose glue between components, this sort of thing is invaluable.

A great example of where this is a good fit is the Ruby OpenStruct class.

like image 179
tadman Avatar answered Sep 21 '22 01:09

tadman