4 ms·
Method_missing considered harmful.
- jamesbritt 15y agoIt's better to explicitly create the methods you want using metaprogramming. Almost. If you know in advance what methods are going to be called then there's little need to use method_missing Anecdotally, the most common use-case is that you don't know exactly what methods need to be handled at run time, but you have a good idea of the boundaries. I.e. you're not planning on handling every message sent to an object, just those that meet some relatively narrow criteria. Most likely these messages will be sent repeatedly, so rather than carry the overhead of method_missing each time, you can use metaprogramming to add methods as encountered. Depending on when in the object life-cycle these methods are added may or may not address the concerns raised in the article. Don't use method_missing to do metaprogramming. It's like writing an entire website in the 404-handler of a web framework. That would only be true if you used method_missing to handle every message sent to all objects. In real life having smarter, dynamic 404 handling makes sense. In fact, most dynamic Web sites are based on the idea of run-time generation of HTML where none previously existed. Add in caching and you have pretty much what I just described for method_missing.