19th
Ruby: hook methods and metaprogramming
Here are a handful of hook methods I’ve used in my Ruby career:
- method_added
- method_missing
- const_added
- const_missing
- inherited
- included
- extended
These methods are called when the appropriate event takes place (e.g. method_missing in rails is used to detect method calls like Model.find_by_other(other) and delegate to the appropriate find(:other => other) method.)
Sometime just detecting the class/module or symbol name being used/defined is not enough. Ruby provides various query methods to provide addition info, such as:
- methods
- instance_methods
- class_methods
- constants
- method_defined?
It’s also possible the behaviour we need to define on the fly is not present in the original class. This is unlike Model.find_by_criterion(c) in rails, which already has a Model.find() method, which needs only be invoked with the correct arguments.
If we need to define the method we’re delegating to at the time of delegation, then we need metaprogramming. Ruby gives us several metaprogramming methods to accomplish this:
- eval
- instance_eval
- class_eval
- define_method
- define_const
I’ll clarify some of my uses of these methods in practice in the next post.