TExcelTAD
Home › Ruby › Ruby Metaprogramming Basics

Ruby Metaprogramming Basics

Metaprogramming means writing code that writes or changes code while the program runs. Ruby is famous for it: attr_accessor, Rails' has_many and RSpec's describe are all metaprogramming. You don't need it every day, but understanding the basics demystifies a lot of Ruby "magic".

Calling methods by name: send

send (and the safer public_send) calls a method whose name is given as a symbol or string — decided at run time:

ruby · try it yourself
text = "Metaprogramming"
%i[upcase downcase length reverse].each do |action|
  puts "#{action}: #{text.public_send(action)}"
end

p 10.public_send(:+, 5)
p [3, 1, 2].public_send("sort")
upcase: METAPROGRAMMING
downcase: metaprogramming
length: 15
reverse: gnimmargorpateM
15
[1, 2, 3]

This is handy when the method name comes from data — a config file, a user choice or a list of fields:

ruby · try it yourself
class Report
  def csv = "a,b,c"
  def html = "<table>...</table>"
  def text = "a b c"
end

format = "html"
report = Report.new
if report.respond_to?(format)
  puts report.public_send(format)
end
<table>...</table>

Note: Never call send with unchecked user input: it can reach private methods. Use public_send and a whitelist of allowed names.

Introspection

Ruby objects can describe themselves:

ruby · try it yourself
class Gadget
  attr_accessor :name, :price
  def initialize(name, price) = (@name, @price = name, price)
  def discounted = price * 0.9
end

g = Gadget.new("Lamp", 40)
p Gadget.instance_methods(false).sort
p g.instance_variables
p g.respond_to?(:discounted)
p Gadget.method_defined?(:price=)
p g.method(:discounted).arity
[:discounted, :name, :name=, :price, :price=]
[:@name, :@price]
true
true
0

define_method: creating methods in a loop

define_method creates a method from a name and a block. It shines when many methods follow the same pattern:

ruby · try it yourself
class Order
  STATUSES = %i[pending paid shipped cancelled].freeze

  attr_reader :status

  def initialize = @status = :pending

  STATUSES.each do |s|
    define_method("#{s}?") { status == s }
    define_method("mark_#{s}!") { @status = s; self }
  end
end

o = Order.new
p o.pending?
o.mark_paid!
p o.paid?
p o.mark_shipped!.shipped?
p Order.instance_methods(false).sort.first(4)
true
true
true
[:cancelled?, :mark_cancelled!, :mark_paid!, :mark_pending!]

Eight methods from four lines. Adding a new status means adding one symbol to the list.

Writing your own attr-style macro

Class-level helpers like attr_accessor are just class methods that call define_method. You can write your own:

ruby · try it yourself
module Defaults
  def attr_with_default(name, default)
    define_method(name) do
      instance_variable_get("@#{name}") || default
    end
    define_method("#{name}=") do |value|
      instance_variable_set("@#{name}", value)
    end
  end
end

class Profile
  extend Defaults
  attr_with_default :theme, "light"
  attr_with_default :language, "en"
end

pr = Profile.new
p pr.theme
pr.theme = "dark"
p pr.theme
p pr.language
"light"
"dark"
"en"

method_missing

When you call a method that doesn't exist, Ruby calls method_missing before raising NoMethodError. Overriding it lets an object respond to any method name:

ruby · try it yourself
class Settings
  def initialize(data) = @data = data

  def method_missing(name, *args)
    key = name.to_s
    if key.end_with?("=")
      @data[key.chomp("=").to_sym] = args.first
    elsif @data.key?(name)
      @data[name]
    else
      super
    end
  end

  def respond_to_missing?(name, include_private = false)
    @data.key?(name.to_s.chomp("=").to_sym) || super
  end
end

s = Settings.new({host: "localhost", port: 3000})
p s.host
s.port = 8080
p s.port
p s.respond_to?(:host)

begin
  s.colour
rescue NoMethodError => e
  puts e.message
end
"localhost"
8080
true
undefined method 'colour' for an instance of Settings

Two rules for method_missing:

  1. Call super for names you don't handle, so real typos still raise NoMethodError.
  2. Also define respond_to_missing?, so respond_to? tells the truth.

Tip: method_missing is slower and harder to debug than real methods. If you know the names in advance, prefer define_method.

Hooks: reacting to events

Ruby calls special methods when certain things happen — a class is inherited, a module is included, a method is added:

ruby · try it yourself
class Plugin
  @registry = []

  class << self
    attr_reader :registry

    def inherited(subclass)
      super
      Plugin.registry << subclass.name
    end
  end
end

class CsvExport < Plugin; end
class PdfExport < Plugin; end

p Plugin.registry
["CsvExport", "PdfExport"]

Frameworks use the inherited hook to register subclasses automatically — no manual list required.

instance_variable_get/set and class_eval

ruby · try it yourself
class Box; end

Box.class_eval do
  def open = "opened!"
end

b = Box.new
b.instance_variable_set(:@label, "fragile")
p b.open
p b.instance_variable_get(:@label)
"opened!"
"fragile"

class_eval reopens a class from a variable or a string; instance_variable_get/set reach inside an object. They are powerful debugging and framework tools — but they bypass encapsulation, so use them sparingly in application code.

Summary

Tool Purpose
send / public_send call a method by name
respond_to? does the object have this method?
define_method create a method dynamically
method_missing + respond_to_missing? handle unknown method calls
instance_variable_get/set read/write instance variables by name
class_eval reopen a class and add code
inherited, included, method_added hooks called by Ruby

Test yourself

What does obj.public_send(:size) do?

  1. Defines a size method
  2. Calls obj.size
  3. Checks whether size exists
  4. Sends obj over the network

When is method_missing called?

  1. Before every method call
  2. When a called method does not exist
  3. When a method raises an error
  4. When a class is defined

Which method should accompany a custom method_missing?

  1. respond_to_missing?
  2. initialize
  3. to_s
  4. define_method