Now, like any other method, method_missing can be overridden. A common rails use, and how I first discovered method_missing, is to simplify database queries and make them more readable. In rails, courtesy of method_missing, you can find_by_any_arbitrary_attribute without having to explicitly write the method to do so - as long as “any_arbitrary_attribute” is a column in your table, method_missing will take care of the rest.
You can do all sorts of tricky things here, which is both an expressive and dangerous feature (an increasingly recurring theme, I find, the more I learn about ruby.) You can do some really neat, useful things, like implement domain specific languages, but you can also do some really stupid, crazy-making things, like accidentally return “true” every time you call a non-existent, or even just a misspelled, method. Less dangerous, but still mildly annoying, is the fact that overriding method_missing can easily cause an object to respond to a method, while respond_to? will still return false for that method name, and the method will not show up in the array .methods returns. The big idea here is that overriding method_missing makes it really easy to make debugging really hard.
There are some ways to avoid making debugging a pain, however. One is to also override respond_to. Alternatively, depending on the expected usage, you might want to have method_missing dynamically construct a method, which will add the method to the methods list, and cause the expected behavior for respond_to. After some failed attempts at using define_method to do this, here’s one way to do this that works:
class MethodMissingTest
def method_missing(method_name)
method_source = "
def #{method_name}
puts 'added a method'
end
"
instance_eval(method_source)
send(method_name)
end
end
Now, you can make a new instance of MethodMissingTest - let's call it "feed_me_methods" and call any random string as a method on feed_me_methods, and feed_me_methods will now actually contain a method by that name, rather than just act like it does.
If you want to play some more with this, Sarah Allen has made a fun test-first xml tag-generator exercise. Cheers, and remember to method_missing responsibly!