I’ve read a few articles lately (like this one), advocating the use for the method_missing method in Ruby.
Many people seem to have a passionate love affair with method_missing, but aren’t very careful in how they handle their relationship. So, I’d like to address the question:
How should I use method_missing?
If you don’t want to read through the reasons you should stay with your companion, define_method, and are just looking to rationalize your love-affair with method_missing, you can skip directly to when to use method_missing.
When to resist method_missing
First of all, never give in to your love affair with method_missing without taking a moment to realize how good you have it. You see, in your day-to-day life, you rarely need method_missing as bad as you think you do.
Day-to-day life: proxy methods
Case: I need to allow one class to use the methods of another class.
This is the most common use-case I’ve seen for method_missing. It’s especially popular in gems and Rails plugins. The pattern goes something like this:
class A
def hi
puts "Hi from #{self.class}"
end
end
class B
def initialize
@b = A.new
end
def method_missing(method_name, *args, &block)
@b.send(method_name, *args, &block)
end
end
A.new.hi #=> Hi from A
B.new.hi #=> Hi from A
(more…)