📎 Webclip
Ruby Metaprogramming - Method Missing
method_missing is a Ruby method for handling calls to methods that do not exist. It gives an object one last chance to deal with the call before Ruby raises an exception. The page shows that it receives the missing method name, any arguments, and an optional block.
Reading notes#
method_missinghandles undefined method calls inside an object.- It receives three parameters: the method name,
*args, and&block. - One use is dealing with repetitive methods that behave the same way, such as generating HTML tags dynamically in a DSL.
- Another use is delegating method calls to another object.
- A
Presenterexample stores an object and forwards missing calls withsend. - A
UserPresenteroverrideslast_nameand lets other calls fall through to the wrapped user object. - The example shows
first_nameandagebeing delegated, whilelast_nameuses the presenter’s own implementation. - The page also recreates
aliasasmimicwith a class-level lookup table. - When a missing method matches an entry in the table, the call is redirected to the aliased method.
- If no alias exists, the code raises an
ArgumentError.
