Metaprogramming
Metaprogramming means writing code that writes or changes code while the program runs. Ruby is famous for it: Rails turns one line like has_many :comments into a dozen methods. You don't need metaprogramming every day, but understanding it explains the "magic" in Ruby libraries, and lets you remove repetition from your own code.
Classes are open
You can reopen any class, including Ruby's own, and add methods:
This is called monkey patching. It's handy in your own code, but changing core classes in a shared library surprises other people. Prefer refinements (see Modules and mixins) or plain helper methods there.
Asking objects about themselves (reflection)
public_send(:name, args) calls a method whose name is in a variable, which is the basis of most metaprogramming.
Defining methods dynamically
define_method creates a method from a name and a block. One loop replaces lots of near-identical methods:
Your own attr_accessor
attr_accessor itself is just a class method that calls define_method. Here's a version that also validates types:
A method called in the class body like typed_attr :age, Integer is a class macro. That's exactly how has_many, validates and before_action work in Rails.
method_missing: handling methods that don't exist
When you call a method an object doesn't have, Ruby calls method_missing before raising NoMethodError. You can intercept it to respond to whole families of names:
Two rules: call super for names you don't handle, and also define respond_to_missing? so respond_to? tells the truth. method_missing is slower and harder to follow than real methods, so prefer define_method when you know the names in advance.
Evaluating code in a context
instance_eval runs a block with self set to an object. It's how Ruby DSLs (domain-specific languages) such as RSpec, Rake and routing files read so naturally:
Inside the block, size and topping are called on the pizza, because instance_eval made it self.
Hooks
Ruby calls special methods when certain things happen, so a class or module can react:
| Hook | Called when |
|---|---|
inherited(sub) |
A class is subclassed |
included(base) / extended(base) |
A module is included / extended |
method_added(name) |
A method is defined |
method_missing / respond_to_missing? |
An unknown method is called / asked about |
Use it wisely
Metaprogramming makes code shorter but harder to search, read and debug. Good uses: removing real repetition, building DSLs, and library code with good tests. If a plain method or a hash would do, use that. In Ruby's own words: "Clever code is code you have to be clever to debug."
Practice
- Add a
Numeric#percent_of(total)method and use it:25.percent_of(200). - Use
define_methodto give aColorclassred?,green?andblue?methods from a list. - Write a class macro
log_calls :save, :deletethat wraps those methods to print their names when called (hint:prependa module built withModule.new). - Write a tiny DSL with
instance_evalthat builds an HTML list:list { item "a"; item "b" }.
1.What does define_method(:paid?) { … } do?
2.When is method_missing called?
3.What does instance_eval change?
4.What is a "class macro"?