Ruby meta: method_missing
This course covers method_missing, the hook Ruby calls after ordinary method lookup up the ancestor chain finds nothing. It explains how the default version on BasicObject raises NoMethodError, and how a class can override it to handle families of calls without a def for each. It shows why an override without super absorbs typos, how calling super restores the error, and why respond_to_missing? must be overridden alongside it. It ends by reading Rails' delegate_missing_to source and building a proxy from the same pieces.
What you'll learn
- ✓How Ruby calls method_missing before raising NoMethodError
- ✓Overriding method_missing to handle a family of related calls
- ✓Calling super for calls your method_missing does not handle
- ✓Overriding respond_to_missing? so respond_to? and method() report correctly
- ✓How Rails' delegate_missing_to uses the method_missing and respond_to_missing? pair
- ✓Building a forwarding proxy with method_missing, respond_to_missing? and super
What happens when a method doesn't exist
NoMethodError has shown up many times in this series: a typo, a method called on the wrong type, a name that doesn't exist on that object.
Read the full lesson free →Curriculum
7 lessonsWhat happens when a method doesn't exist
Ruby calls method_missing after a failed lookup, and BasicObject's default version is what raises NoMethodError.
Overriding method_missing
The method_missing signature, and one override answering a family of calls like DynamicPoint's x, y and z.
The danger of forgetting super
A method_missing with no fallback absorbs every name, so typos return normal values instead of raising errors.
Calling super for what you don't handle
An if/else with super in the else branch makes unhandled calls raise NoMethodError again.
respond_to_missing?: the companion method
Overriding respond_to_missing? with the same condition makes respond_to? and method() agree with method_missing.
delegate_missing_to in Rails' source
Reading Rails' delegate_missing_to source and its hand-written example of the method_missing and respond_to_missing? pair.
Putting it together: closing the series
A build_proxy method combines forwarding method_missing, matching respond_to_missing? and super, in the shape of delegate_missing_to.