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:
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:
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
sendwith unchecked user input: it can reach private methods. Usepublic_sendand a whitelist of allowed names.
Introspection
Ruby objects can describe themselves:
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:
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:
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:
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:
- Call
superfor names you don't handle, so real typos still raiseNoMethodError. - Also define
respond_to_missing?, sorespond_to?tells the truth.
Tip:
method_missingis slower and harder to debug than real methods. If you know the names in advance, preferdefine_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:
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
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?
- Defines a size method
- Calls obj.size
- Checks whether size exists
- Sends obj over the network
When is method_missing called?
- Before every method call
- When a called method does not exist
- When a method raises an error
- When a class is defined
Which method should accompany a custom method_missing?
respond_to_missing?initializeto_sdefine_method