Metaprogramming Techniques

Metaprogramming Techniques in Ruby: --- In the back of a trophy and sign shop stands a pantograph engraver: a jointed brass linkage with a blunt stylus at one…


The Analogy: The Sign Shop's Pantograph Engraver

In the back of a trophy and sign shop stands a pantograph engraver: a jointed brass linkage with a blunt stylus at one end and a spinning cutter at the other. The operator clamps a master template -- a single raised brass letter, say a capital R -- onto the bed, and traces its outline with the stylus. The linkage repeats every motion at the cutter, and the same R is engraved into the workpiece. The operator never cuts a letter freehand. They set up a master and let the machine reproduce it.

The power of the machine is that one template makes any number of copies. Set up the R, and you can engrave it onto forty name badges without touching the shape again. Swap the template for an S and every badge now gets an S. The letters on the finished badges were never written by hand and were never stored anywhere as finished letters -- they were generated, at the moment of engraving, from one master and a tracing motion. The shop keeps a small rack of master templates, not a drawer full of every letter it has ever cut.

There is a second machine beside it, subtler and more dangerous: a follower that engraves whatever groove the stylus happens to fall into. Give it a proper master and it behaves. Give it a scratched, ambiguous plate and it will faithfully engrave the scratch, because it has no notion of which grooves are letters and which are damage. It does not refuse bad input; it reproduces it. Its usefulness and its hazard are the same property -- it will trace anything.

The engraver fails in four ways. A master clamped in crooked engraves the same tilt onto every badge, so one setup error is stamped across the whole run rather than caught on the first piece. The follower that traces any groove will happily engrave a misspelling, because a plausible-looking scratch is indistinguishable to it from a real letter -- the badge comes out wrong but finished. The finished letters appear in no drawing and no cut-list, so a shop foreman who searches the paperwork for "R" finds nothing and concludes the badge was never made. And the shop's catalogue, which lists the templates on the rack, says nothing about what the follower can trace, so the advertised capability and the real one disagree. Ruby's define_method, method_missing, and send reproduce all four exactly.


Syntax or Core Structure

define_method is the pantograph: it clamps one master -- the block you give it -- and stamps out a real method from it, once per item in whatever data you drive it with. The methods it makes are ordinary methods; the only unusual thing is that they were generated from a loop rather than typed out.

# engraver.rb -- one template, many engraved methods.

class Plate
  FIELDS = [:name, :rank, :room]

  def initialize(values)
    @values = values
  end

  FIELDS.each do |field|
    define_method(field) do
      @values[field]
    end

    define_method("#{field}=") do |value|
      @values[field] = value
    end

    define_method("#{field}_engraved?") do
      !@values[field].nil?
    end
  end
end

plate = Plate.new(name: "Ada", rank: "Captain", room: nil)
puts plate.name
puts plate.rank
puts plate.room_engraved?
plate.room = "204"
puts plate.room
puts plate.room_engraved?

puts Plate.instance_methods(false).sort.inspect
puts plate.respond_to?(:name)
puts plate.respond_to?(:salary)
puts plate.send(:rank)

Output:

Ada
Captain
false
204
true
[:name, :name=, :name_engraved?, :rank, :rank=, :rank_engraved?, :room, :room=, :room_engraved?]
true
false
Captain

Nine methods came off one template. The FIELDS.each loop ran three times, and each pass called define_method three times -- a reader, a writer, and an _engraved? predicate -- so Plate ends up with nine real instance methods without nine method definitions in the source. plate.name returns "Ada" from the hash; plate.room_engraved? is false because the room started as nil; and after plate.room = "204" runs the generated writer, the same predicate is true.

The block passed to define_method is the master, and it closes over field. Each of the three passes captures its own field -- :name, then :rank, then :room -- so the reader defined in the first pass reads :name forever, not whatever field happened to hold when the loop finished. This is the single most important property of define_method over the older string-eval approach: the value is captured cleanly at definition time, the way a template is clamped before the run starts.

The last four lines show the methods are genuinely real. instance_methods(false) lists exactly the nine that were engraved, sorted for a stable printout; respond_to?(:name) is true because name is a real method, while respond_to?(:salary) is false because no template ever engraved it; and send(:rank) calls the reader by its symbol name, which is how you dispatch a method whose name you only learn at runtime. Note that initialize does not appear in the list -- it is private, and instance_methods reports only public and protected methods.


Technical Depth: The Follower, And What It Traces

define_method engraves a fixed set of methods from a template you control. method_missing is the other machine -- the follower that engraves whatever groove the call falls into. It runs only when a call finds no real method, and whatever it does with that call becomes the object's apparent behaviour. It is the most powerful tool in the chapter and the one that most often traces a scratch.

The Three Tools, And When Each One Runs

ToolWhat it doesWhen it runsThe hazard
define_methodcreates a real, named method from a blockonce, at definition timea bug in the template is stamped onto every generated method
method_missingintercepts calls to methods that do not existat call time, only after lookup failsit answers calls you never meant to support, including typos
respond_to_missing?teaches respond_to? about method_missing methodswhen respond_to? is askedforgetting it makes respond_to? lie about what the object handles
sendcalls a method by its symbol nameat call timeit reaches private methods too, so it can bypass an interface
public_sendcalls a method by name, public onlyat call timenone beyond ordinary dispatch; this is the safe default

The row that pairs with method_missing is respond_to_missing?, and leaving it out is the classic bug. If an object answers total_glue through method_missing but respond_to?(:total_glue) returns false, then the object handles a message it denies handling -- the catalogue on the wall disagrees with what the follower will actually trace. Any code that checks respond_to? before calling will wrongly skip the object.

method_missing Answers Calls That Were Never Defined

class Ledger
  def initialize
    @entries = Hash.new(0)
  end

  def record(item, pence)
    @entries[item] += pence
  end

  def method_missing(name, *args)
    text = name.to_s
    if text.start_with?("total_")
      item = text.sub("total_", "").to_sym
      @entries[item]
    else
      super
    end
  end

  def respond_to_missing?(name, include_private = false)
    name.to_s.start_with?("total_") || super
  end
end

led = Ledger.new
led.record(:paint, 450)
led.record(:paint, 150)
led.record(:brass, 800)

puts led.total_paint
puts led.total_brass
puts led.total_glue
puts led.respond_to?(:total_paint)
puts led.respond_to?(:record)
puts led.respond_to?(:sand_it)

begin
  led.sand_it
rescue NoMethodError => e
  puts "raised #{e.class}"
end

Output:

600
800
0
true
true
false
raised NoMethodError

The total_paint and total_brass calls hit no real method, so Ruby routes them to method_missing, which recognises the total_ prefix and returns the summed entry: paint was recorded twice, 450 plus 150, so total_paint is 600. Crucially respond_to?(:total_paint) is true because respond_to_missing? was defined to agree with method_missing; the catalogue matches the follower. And sand_it, which does not match the prefix, falls through to super -- the original method_missing -- which raises NoMethodError, exactly as an undefined method should.

The dangerous line is total_glue, which prints 0. Glue was never recorded, but @entries is a Hash.new(0), so the missing key returns the default zero and the call looks successful. A typo like total_pait would do the same: it matches the total_ prefix, so method_missing handles it and returns 0 rather than raising. The follower traced a plausible scratch. This is the price of method_missing -- it answers a whole family of calls by pattern, and it cannot tell a real member of the family from a misspelling that happens to fit the pattern.

send Reaches Private Methods; public_send Does Not

class Machine
  def start = "running"

  private

  def calibrate = "calibrated"
end

m = Machine.new
puts m.send(:start)
puts m.send(:calibrate)
puts m.public_send(:start)

begin
  m.public_send(:calibrate)
rescue NoMethodError => e
  puts "public_send blocked: #{e.class}"
end

Output:

running
calibrated
running
public_send blocked: NoMethodError

Both send and public_send call a method by a name computed at runtime, which is what makes data-driven dispatch possible. The difference is the guard rail: send ignores private, so m.send(:calibrate) reaches a method the class deliberately hid, while public_send respects the boundary and raises. When the method name comes from anywhere a user can influence -- a params hash, a config file, a message field -- public_send is the only safe choice, because send turns "call this method" into "call any method on this object", which is the follower tracing a groove an attacker cut.


Real World Example: A Form Built From A Schema

A form is a natural fit for the pantograph. You declare the fields once as data, and define_method engraves a reader and a writer for each, while the same declaration records which fields are required so the form can report what is still missing. The program below defines a Form base class whose field method is the engraver, then declares a Booking with four fields and runs three booking records through it.

# form.rb -- declare fields as data, engrave the accessors.

class Form
  def self.field(name, required:)
    @schema ||= {}
    @schema[name] = required

    define_method(name) { @values[name] }
    define_method("#{name}=") { |value| @values[name] = value }
  end

  def self.schema
    @schema
  end

  def initialize(values = {})
    @values = values
  end

  def missing
    self.class.schema.select { |name, required| required && @values[name].nil? }.keys
  end

  def complete?
    missing.empty?
  end
end

class Booking < Form
  field :guest,  required: true
  field :room,   required: true
  field :nights, required: true
  field :notes,  required: false
end

puts "fields: #{Booking.schema.keys.sort.inspect}"

rows = [
  { guest: "Ada",   room: "204", nights: 3 },
  { guest: "Grace", room: "118" },
  { guest: "Alan",  room: "301", nights: 1, notes: "late" },
]

forms = rows.map { |r| Booking.new(r) }
forms.each_with_index do |f, i|
  status = f.complete? ? "complete" : "missing #{f.missing.sort.inspect}"
  puts format("  booking %d: %-8s %s", i + 1, f.guest, status)
end

done = forms.count(&:complete?)
puts "complete #{done} of #{forms.size}"
puts "methods: #{Booking.instance_methods(false).sort.inspect}"

Output:

fields: [:guest, :nights, :notes, :room]
  booking 1: Ada      complete
  booking 2: Grace    missing [:nights]
  booking 3: Alan     complete
complete 2 of 3
methods: [:guest, :guest=, :nights, :nights=, :notes, :notes=, :room, :room=]

The Booking class has no accessor methods written in its body -- only four field declarations. Each declaration recorded whether the field is required and engraved a reader and a writer, which is why the final line lists eight real instance methods that no one typed. The fields: line is the schema's keys sorted, and the methods: line is the eight generated methods sorted, so both are stable regardless of the order Ruby stores them internally.

The three bookings exercise the required bookkeeping the schema captured. Booking 1 supplies guest, room, and nights, so it is complete even though it omits the optional notes. Booking 2 omits nights, which is required, so missing reports [:nights] and the booking is incomplete. Booking 3 supplies everything, including the optional notes, and is complete. The complete 2 of 3 line is count(&:complete?) over the collection, and it reconciles by hand: bookings 1 and 3 are complete, booking 2 is not.

Every value in that output was derived from the four field declarations, and the fact that missing knows nights is required while notes is not comes entirely from the required: flag stored at declaration time. The reader and writer for each field behave identically because they came off one template -- change the template once and all eight methods change together.

The design flaw is where the schema lives. @schema is a class-instance variable, and those are not inherited: a class EventBooking < Booking that declares one field of its own gets a @schema holding only that field, silently losing guest, room, and nights -- and a subclass that declares no fields at all has @schema still nil, so its first call to missing runs nil.select and raises NoMethodError. The engraver clamped the master to the wrong bed. Three narrower faults sit alongside it: complete? checks only for nil, so nights = "three" counts as complete even though a night count should be a number, because the schema records that a field is required but never what type it must be; Form.schema returns the live internal hash rather than a copy, so a caller who writes Booking.schema[:guest] = false mutates validation for every instance ever created; and because the accessors are engraved with define_method, a field named to collide with an existing method -- field :class -- would overwrite it without warning, since define_method traces whatever name it is given.


Common Mistakes

  1. Defining method_missing without respond_to_missing?. The object then answers calls it denies handling: respond_to? returns false for a message method_missing will happily process. Any caller that checks before calling skips the object, and duck-typing quietly breaks. Define the two together, every time.
  1. A method_missing that never calls super. If the fallthrough branch returns nil or a default instead of calling super, every misspelled method name succeeds silently. The undefined-method safety net is gone, and obj.total_pait returns a plausible zero rather than raising. Always end method_missing with super for names you do not handle.
  1. Using send when public_send was meant. send reaches private methods, so dispatching a name that came from user input with send lets a caller invoke anything on the object. Unless you specifically need to call a private method from inside the class, use public_send, which respects the interface.
  1. Reaching for metaprogramming when a loop or a hash would do. define_method and method_missing earn their cost only when the set of methods is genuinely open or data-driven. For three known accessors, three attr_accessor lines are clearer, greppable, and faster. Clever generation of code that could have been written plainly is a maintenance tax with no return.
  1. Generating methods no one can find. A method created by define_method appears in no source search for its name, so the next developer greps for total_paint, finds nothing, and concludes it does not exist. When you generate methods, leave a comment at the generation site listing what gets made, or the code becomes unsearchable.
  1. Capturing the wrong variable in a definition loop. The block passed to define_method closes over loop variables, so relying on a variable that the loop reassigns -- rather than the block parameter -- makes every generated method see the final value. Drive the loop with the value as a block parameter so each definition captures its own.
  1. Opening a core class to add a method that collides. Reopening String or Array to add a method whose name a future Ruby version also adds, or that another library also defines, produces a silent conflict whose winner depends on load order. Refine narrowly or use your own class rather than monkey-patching the standard library.
  1. Letting method_missing mask real errors. A broad method_missing can swallow a genuine NoMethodError from a bug deep inside the object, turning a clear crash into mysterious wrong behaviour. Keep the matched pattern as narrow as possible and let everything else reach super.
  1. Believing generated code is validated code. define_method engraves whatever name it is handed, including one that overwrites an existing method or shadows an inherited one. The machine traces the groove without judging it, so a field named after a real method silently replaces that method. Validate names before you generate.

Best Practices

  • Prefer define_method over string eval. It captures its scope cleanly, it is checked as ordinary Ruby, and it cannot smuggle interpolated text into a definition, which is both safer and easier to reason about.
  • Define respond_to_missing? whenever you define method_missing, and make the two agree on exactly which names are handled. The object's advertised capability must match what it will actually do.
  • End every method_missing with super for the names you do not handle, so undefined methods still raise NoMethodError and typos surface instead of returning a quiet default.
  • Reach for public_send by default and keep send for the rare case where you must call a private method deliberately from inside the object. Never pass a user-supplied name to send.
  • Metaprogram only when the method set is open or driven by data that changes. When the methods are known and few, write them out; plain code that can be searched and read beats generated code that cannot.
  • Leave a signpost at every generation site. A short comment naming the methods a loop creates restores the searchability that define_method takes away, so the next reader can find where a method came from.
  • Keep the matched surface of method_missing as narrow as the feature needs. A tight prefix or a fixed list limits how many typos and how many real bugs the follower can silently trace.
  • Avoid monkey-patching core classes. If you must extend behaviour, use a refinement scoped to where it is needed or a class of your own, so you do not collide with the standard library or another gem.

Practice Exercises

  1. Fix the inheritance flaw. Change Form so the schema is inherited: when a subclass is created, copy the parent's schema into it, so EventBooking < Booking starts with guest, room, and nights and can add its own fields. Show that a subclass with one new field has all five, and that a subclass with no fields no longer raises on missing.
  1. Add respond_to_missing? to a follower. Write a Config class whose method_missing returns a stored setting for any name matching a known key and calls super otherwise, then add respond_to_missing? so respond_to? agrees. Demonstrate with output that a known key returns true and answers, while an unknown one returns false and raises.
  1. Close the send hole. Take the Machine class from the Technical Depth section and write a run(name) method that dispatches name with public_send, then show that a public action runs while a private one raises. Then show the difference by swapping in send and demonstrating that it now reaches the private method.
  1. Add type-checking to the schema. Extend field to record an expected type alongside required:, and change complete? so a field is satisfied only when its value is present and of the right type. Show that a booking with nights set to the string "three" is now reported incomplete, while one with nights set to 3 is complete.