Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 134 ยท Metaprogramming

Introduction to Metaprogramming

A friendly introduction to Ruby metaprogramming - send and public_send, define_method, instance_variable_get and set, Class.new, hooks and the rules for using it responsibly.

Metaprogramming means writing code that writes or inspects code while the program runs. It sounds exotic, yet you have already used it: attr_accessor :name is a method that creates two methods for you. Rails's has_many, RSpec's describe, and Struct.new are all metaprogramming. Ruby makes it natural because classes are ordinary objects (The Ruby Object Model) and methods are looked up at call time.

This lesson is a gentle tour of the core tools: calling methods by name with send and public_send, defining methods dynamically with define_method, reading and writing instance variables, creating classes at runtime, and a first look at hooks. We will also cover the most important part: when not to do it. The next lessons go deeper into define_method, Hooks and Callbacks and Reflection.

Calling a method by name: send and public_send

Normally the method name is fixed in your source: user.name. With send the name is data, so it can come from a variable, a config file or a loop.

Ruby Choosing the method at runtime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

send ignores visibility, so it can call the private secret. public_send respects it and raises NoMethodError with the message private method 'secret' called for an instance of Report. Rule of thumb: use public_send whenever the name could come from outside your code, otherwise a user could trigger private methods. Reserve send for tests and framework internals.

Never pass raw user input to send. obj.send(params[:action]) lets a visitor call :destroy, :eval, :exit... Whitelist the allowed names first, for example ALLOWED = %w[daily weekly].

Asking what an object can do

Metaprogramming starts with questions. respond_to? checks that a method exists, methods and instance_methods(false) list them.

Ruby Asking an object about its methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

This is the basis of duck typing (Duck Typing and Polymorphism): instead of asking "what class are you?", ask "can you do this?".

Reading and writing instance variables

instance_variable_get and instance_variable_set reach a variable by name, even without an accessor. Names start with @.

Ruby Peeking at and filling instance variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The last call fails with 'x' is not allowed as an instance variable name. The Settings class turns a hash into instance variables in one line, which is how many small object-from-hash helpers work. It also shows the cost: nothing documents which variables Settings has, so the class is hard to read. Use it for generic infrastructure, not business logic.

Defining methods dynamically: define_method

A def fixes the method name in the source. define_method takes the name as an argument and the body as a block, so you can generate many similar methods in a loop. It runs inside the class body, where self is the class.

Ruby Generating methods in a loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Three predicate methods came from one loop over STATES. The second class shows a class macro: counter :small, 1 is an ordinary class method that calls define_method, exactly how attr_accessor and Rails's validates work. The blocks are closures, so step and state stay available inside the generated methods. More in define_method and Dynamic Methods.

Creating classes and modules at runtime

A class keyword is not the only way to make a class. Class.new builds one from a block, and const_set gives it a name.

Ruby Class.new and const_set

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Each loop pass builds a subclass of Animal whose speak returns its own sound. Until a class is assigned to a constant it is anonymous, so anonymous.name is nil. This is how libraries build per-model or per-endpoint classes from configuration.

A first look at hooks

Ruby calls special methods when something happens to a class: when it is subclassed (inherited), when a module is included (included) or when a method is added (method_added). Define them to react.

Ruby Reacting to inheritance and include

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Defining inherited gave us a plugin registry for free: every subclass registers itself. The included hook is the classic way a module also adds class methods (via extend) when included. All hooks are detailed in Hooks and Callbacks.

What can go wrong

Metaprogramming trades clarity for flexibility, and the bill arrives later:

  • Searchability: grep draft? finds nothing when the method is generated. Readers and tools cannot see it.
  • Debugging: stack traces point into the generating code, not a clear def.
  • Security: send / eval with user input is an injection hole.
  • Performance: define_method methods are generally as fast to call as def for plain bodies, but send and method_missing carry overhead in hot loops.
  • Surprises for the next developer: the more dynamic the code, the more tests and documentation it needs.

Use these rules:

  1. Try plain code first. A loop or three explicit defs are often better than a macro.
  2. Use metaprogramming where it removes real, repeated boilerplate, in library-style code.
  3. Keep the dynamic part small, name it clearly and document the generated methods in a comment.
  4. Prefer public_send, define_method and instance_variable_get over string eval. Avoid eval unless nothing else works (eval and Binding).
  5. When using method_missing, always add respond_to_missing? (method_missing and respond_to_missing?).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between send and public_send?

    send ignores private and protected. public_send raises NoMethodError for them, which is the safer choice for names from outside.
  2. 2. Which line correctly defines a method named draft? dynamically inside a class body?

    define_method takes the name and a block that becomes the method body.
  3. 3. What does Class.new(Animal) without an assignment to a constant return?

    It returns a new class object. It has no name until it is assigned to a constant.
  4. 4. Which hook runs when a class is subclassed?

    Ruby calls inherited(subclass) on the parent class each time a subclass is created.
  5. 5. Which is a good reason to avoid heavy metaprogramming?

    Dynamic methods do not appear in the source text, so readers, grep and debuggers have a harder time.

Summary

  • Metaprogramming is code that creates or inspects code at runtime; attr_accessor is a familiar example.
  • send calls any method by name (even private); public_send respects visibility and is safer for outside input.
  • respond_to?, methods, instance_variable_get and instance_variable_set let you ask and change objects dynamically.
  • define_method generates methods from a loop or a class macro; closures keep their variables.
  • Class.new and const_set build classes at runtime; hooks like inherited and included let classes react to events.
  • Use it sparingly, keep the dynamic part small, and never feed untrusted input into send or eval.

Next: define_method and Dynamic Methods