Composition and delegation
suggest changeComposition means building an object out of other objects that it holds in instance variables, instead of inheriting their behavior from a superclass. Inheritance says "a Stack is an Array". Composition says "a Stack has an Array" and decides for itself which of the array's abilities to expose.
Delegation is how composition is usually wired up: the outer object receives a message and forwards it to the inner object. Ruby gives you several ways to do it:
- plain methods that forward by hand
Forwardable(standard library): declares forwarding methods in one lineSimpleDelegatorandDelegateClass(standard librarydelegate): wrap an object and forward everything, overriding only what you wantmethod_missing: dynamic forwarding written by handdelegatefrom ActiveSupport, in Rails apps
All examples below run on plain Ruby 3.3+ (tested on Ruby 4.0) with no gems.
Why not just inherit?
Subclassing a core class to get its behavior is tempting and short:
class Stack < Array
def peek = last
end
s = Stack.new
s.push(1)
s.push(2)
s.insert(0, 99) # not a stack operation, but it works
s.shift
p s
p s.peek
p (s + [3]).class
[1, 2]
2
Array
Stack now has 136 extra public methods inherited from Array, including insert, shift and []=, which let callers break the "last in, first out" rule. Many of them also return a plain Array, so the "stack" quietly stops being a stack. And once code starts relying on Stack#sort or Stack#[], you can never change how a stack is stored.
Composition keeps the interface small and the storage private:
class Stack
def initialize
@items = []
end
def push(item)
@items.push(item)
self
end
def pop = @items.pop
def peek = @items.last
def empty? = @items.empty?
def size = @items.size
end
s = Stack.new
s.push(1).push(2).push(3)
p s.pop
p s.peek
p s.size
begin
s.insert(0, 99)
rescue NoMethodError => e
puts e.message
end
3
2
2
undefined method 'insert' for an instance of Stack
The one-line methods that just call @items are delegation done by hand. That is perfectly good Ruby, and it is the fastest option. It also lets you change the result, as push does here by returning self so calls can be chained. When there are many such methods, Forwardable removes the repetition.
A rule of thumb: inherit when the subclass really is a special case of the parent and should support its entire interface (see Inheritance). Use composition when you only want some of another object's behavior, when you might swap the collaborator later, or when you want to combine behaviors from several objects.
Forwardable
Forwardable is in the standard library. You extend it in a class, which adds class-level macros that define forwarding methods:
def_delegators accessor, *methods: forward each method under the same namedef_delegator accessor, method, new_name = method: forward one method, optionally under another name
The accessor can be an instance variable (:@items), a method name (:user), or a string of Ruby code ("self.class").
require "forwardable"
class Stack
extend Forwardable
def_delegators :@items, :size, :empty?, :clear, :each
def_delegator :@items, :push, :<<
def_delegator :@items, :pop
def_delegator :@items, :last, :peek
include Enumerable
def initialize(*items)
@items = items
end
end
s = Stack.new(1, 2)
s << 3
s << 4
p s.size
p s.peek
p s.pop
p s.map { _1 * 10 }
p s.include?(2)
p s.respond_to?(:insert)
4
4
4
[10, 20, 30]
true
false
Delegating each and including Enumerable is a common trick: one forwarded method gives the class map, select, include?, sort_by and the rest of Enumerable, while insert and []= stay hidden.
Forwardable defines real methods, so they appear in instance_methods, show up in respond_to?, and have nearly the speed of hand-written ones.
delegate: the hash form
delegate (also available as instance_delegate) takes a hash that maps method names to an accessor. It is handy when a class forwards to several collaborators:
require "forwardable"
User = Data.define(:name, :email)
Address = Data.define(:city, :country)
class Order
extend Forwardable
attr_reader :user, :address, :lines
delegate %i[name email] => :user
delegate city: :address, country: :address
def_delegator :user, :name, :customer_name
def_delegator :lines, :sum, :total
def_delegator "self.class", :tax_rate
def self.tax_rate = 0.23
def initialize(user:, address:, lines:)
@user, @address, @lines = user, address, lines
end
end
o = Order.new(
user: User.new("Alice", "alice@example.com"),
address: Address.new("Warsaw", "PL"),
lines: [10, 25, 7]
)
puts o.name, o.email, o.city, o.customer_name
p o.total
p o.tax_rate
p Order.instance_method(:name).owner
Alice
alice@example.com
Warsaw
Alice
42
0.23
Order
Arguments and blocks are passed through unchanged, so o.total could also be called as o.total { _1 * 2 }.
Gotcha: return values and nil targets
A forwarded method returns whatever the target returns. Array#push returns the array, so the delegated << hands your private @items to the caller:
require "forwardable"
class Stack
extend Forwardable
def_delegator :@items, :push, :<<
def initialize = @items = []
end
s = Stack.new
p (s << 1).class
Array
Write that method by hand (def <<(item) = (@items << item; self)) when the return value matters. The same applies to any delegated method that returns the internal object or a mutable part of it.
If the target is nil, you get a NoMethodError that names nil, not your class. Ruby also prints a confusing "forwarding to private method" warning, because Forwardable can't tell a missing method from a private one:
require "forwardable"
class Order
extend Forwardable
attr_accessor :user
def_delegator :user, :name
end
o = Order.new
begin
o.name
rescue NoMethodError => e
puts e.message
end
class Order
def name = user&.name
end
p o.name
order.rb:11: warning: Order#name at order.rb:6 forwarding to private method NilClass#name
undefined method 'name' for nil
nil
When the collaborator is optional, write the method by hand with &., as shown above.
SingleForwardable: delegation on modules and single objects
SingleForwardable provides the same macros for singleton methods. That is useful for a module-level facade:
require "forwardable"
require "logger"
module App
extend SingleForwardable
def self.logger
@logger ||= Logger.new($stdout, formatter: ->(sev, _, _, msg) { "#{sev}: #{msg}\n" })
end
def_delegators :logger, :info, :warn
def_delegator :ENV, :fetch, :env
end
App.info("starting")
App.warn("disk almost full")
p App.env("HOME", "?").start_with?("/")
INFO: starting
WARN: disk almost full
true
SimpleDelegator: wrap everything, override a few
Sometimes you want an object that behaves exactly like another object, except for a few methods. Listing every method with Forwardable would be impractical. SimpleDelegator forwards every method it doesn't define to the wrapped object, and super inside an overriding method calls the wrapped object's version.
This is the usual way to write presenters and decorators:
require "delegate"
require "date"
User = Struct.new(:first_name, :last_name, :born_on)
class UserPresenter < SimpleDelegator
def full_name = "#{first_name} #{last_name}"
def born_on
super.strftime("%B %-d, %Y")
end
end
user = User.new("Ada", "Lovelace", Date.new(1815, 12, 10))
view = UserPresenter.new(user)
puts view.full_name
puts view.born_on
puts view.first_name
view.first_name = "Augusta"
puts user.first_name
p view.class
p view.is_a?(User)
p view == user
p user == view
p view.equal?(user)
p view.__getobj__.equal?(user)
p view.respond_to?(:last_name)
Ada Lovelace
December 10, 1815
Ada
Augusta
UserPresenter
false
true
false
false
true
true
Note:
- Calls without an override, including setters like
first_name=, go to the wrapped object and change it. __getobj__returns the wrapped object, and__setobj__(obj)swaps it for another.- The wrapper is not the original.
class,is_a?andequal?describe the wrapper.view == useristruebecause the delegator compares the wrapped object, butuser == viewisfalse, sinceStruct#==checks the class of the other side. Code that doescase obj when Userwon't recognise the wrapper either.
Stacking decorators
Delegators can wrap other delegators, so behavior can be added in layers at runtime without a subclass for every combination:
require "delegate"
class Coffee
def cost = 2.00
def description = "coffee"
def receipt = "#{description}: $#{format("%.2f", cost)}"
end
class WithMilk < SimpleDelegator
def cost = super + 0.50
def description = "#{super} with milk"
end
class WithSyrup < SimpleDelegator
def initialize(drink, flavor)
super(drink)
@flavor = flavor
end
def cost = super + 0.75
def description = "#{super} with #{@flavor} syrup"
end
drink = WithSyrup.new(WithMilk.new(Coffee.new), "vanilla")
puts drink.description
puts drink.cost
puts drink.receipt
coffee with milk with vanilla syrup
3.25
coffee: $2.00
The last line is the classic delegation trap, sometimes called self schizophrenia. receipt isn't overridden, so it runs inside the inner Coffee, where self is the coffee. The coffee calls its own description and cost and never sees the decorators. Inheritance and modules (extend, prepend) don't have this problem because there is only one self. If the wrapped object calls methods that the decorator changes, either override the calling method too or use the module approach from Decorator Pattern.
When a subclass of SimpleDelegator defines initialize, it must call super(obj) with the wrapped object, as WithSyrup does.
DelegateClass: delegation with real methods
SimpleDelegator finds methods at call time through method_missing. DelegateClass(SomeClass) instead builds a superclass that defines a forwarding method for every public instance method of SomeClass. You use it the same way:
require "delegate"
class Account
attr_reader :balance
def initialize(balance) = @balance = balance
def withdraw(amount)
raise ArgumentError, "insufficient funds" if amount > balance
@balance -= amount
end
end
class AuditedAccount < DelegateClass(Account)
attr_reader :log
def initialize(account)
super
@log = []
end
def withdraw(amount)
@log << "withdraw #{amount}"
super
end
end
acct = AuditedAccount.new(Account.new(100))
acct.withdraw(30)
p acct.balance
p acct.log
acct.__setobj__(Account.new(5))
p acct.balance
begin
acct.withdraw(10)
rescue ArgumentError => e
p e.message
end
p acct.log
70
["withdraw 30"]
5
"insufficient funds"
["withdraw 30", "withdraw 10"]
Prefer DelegateClass when you know the wrapped type up front. It is faster (see the benchmark below), and the forwarded methods are visible to instance_methods and to documentation tools. Use SimpleDelegator when the wrapped object can be of any class.
Delegation with method_missing
You can build your own dynamic delegator with method_missing. This makes sense when you need to do something for every forwarded call, such as logging, counting or access checks:
class Recorder
attr_reader :calls
def initialize(target)
@target = target
@calls = []
end
def method_missing(name, *args, **kwargs, &block)
if @target.respond_to?(name)
@calls << name
@target.public_send(name, *args, **kwargs, &block)
else
super
end
end
def respond_to_missing?(name, include_private = false)
@target.respond_to?(name, include_private) || super
end
end
r = Recorder.new([3, 1, 2])
p r.sort
p r.map { _1 * 2 }
p r.respond_to?(:each)
p r.method(:size).call
p r.calls
begin
r.fly
rescue NoMethodError => e
puts e.message
end
[1, 2, 3]
[6, 2, 4]
true
3
[:sort, :map, :size]
undefined method 'fly' for an instance of Recorder
Rules for doing this correctly:
- Always call
superfor names you don't handle. Otherwise typos are silently swallowed and returnnil. - Always define
respond_to_missing?, sorespond_to?andmethod(:name)work. - Use
public_send, notsend, so you don't expose the target's private methods. - Pass
*args, **kwargs, &block(or just...) so keyword arguments and blocks reach the target.
This style is common in proxies (see Proxy). For plain forwarding, SimpleDelegator already does all of this for you.
Composing behavior from collaborators
Delegation isn't only about wrapping. Often the outer object's job is to coordinate several small objects, each with one responsibility, and you choose the parts when you create it:
require "json"
class CsvFormatter
def format(rows) = rows.map { _1.join(",") }.join("\n")
end
class JsonFormatter
def format(rows) = JSON.generate(rows)
end
class MemoryStore
attr_reader :saved
def initialize = @saved = {}
def write(name, data) = @saved[name] = data
end
class Report
def initialize(formatter:, store:)
@formatter = formatter
@store = store
end
def publish(name, rows)
@store.write(name, @formatter.format(rows))
end
end
store = MemoryStore.new
rows = [["id", "name"], [1, "Ada"], [2, "Linus"]]
Report.new(formatter: CsvFormatter.new, store: store).publish("users.csv", rows)
Report.new(formatter: JsonFormatter.new, store: store).publish("users.json", rows)
store.saved.each { |name, data| puts "#{name}:", data, "" }
users.csv:
id,name
1,Ada
2,Linus
users.json:
[["id","name"],[1,"Ada"],[2,"Linus"]]
With inheritance this would take CsvFileReport, JsonFileReport, CsvS3Report and so on: one class per combination. With composition, any formatter that responds to format works with any store that responds to write. Duck typing means no shared base class or interface declaration is needed. Passing the parts in through the constructor is Dependency injection, and it also makes Report easy to test with fake stores.
delegate in Rails (ActiveSupport)
Rails apps usually use ActiveSupport's Module#delegate instead of Forwardable. It adds options for prefixes and nil targets:
class Order < ApplicationRecord
belongs_to :user
delegate :name, :email, to: :user # order.name
delegate :name, to: :user, prefix: true # order.user_name
delegate :name, to: :user, prefix: :customer # order.customer_name
delegate :city, to: :address, allow_nil: true # nil instead of NoMethodError
delegate :tax_rate, to: :class # Order.tax_rate
delegate :name, to: :user, private: true # private forwarding method
end
class OrderPresenter
delegate_missing_to :@order # forward everything else
def initialize(order) = @order = order
end
allow_nil: true returns nil when the target is nil, which fixes the Forwardable nil gotcha shown above. delegate_missing_to is a method_missing delegator with respond_to_missing? already defined. Outside Rails, stick to the standard library.
Performance
Calling a method of Target 5 million times through each kind of wrapper (Ruby 4.0, one core, with Benchmark's realtime):
direct call 42.5 M calls/s
manual method 31.6 M calls/s
Forwardable 16.3 M calls/s
DelegateClass 17.6 M calls/s
SimpleDelegator 3.0 M calls/s
method_missing 5.5 M calls/s
Forwardable and DelegateClass generate code that checks the target and handles errors, so they are about half as fast as a hand-written method. Anything that goes through method_missing is another 3 to 6 times slower. That rarely matters, since even the slowest path costs about 0.3 microseconds per call. But for a delegator used in a hot loop, prefer explicit methods or Forwardable.
Choosing an approach
| You want to... | Use |
|---|---|
| Expose a few methods of an inner object | Forwardable (def_delegators, delegate) |
| Expose a method under a different name or change its result | a hand-written method |
| Wrap an object and change a few methods (decorator, presenter) | SimpleDelegator |
| Same, when the wrapped class is known and speed or introspection matters | DelegateClass(Klass) |
| Intercept every call (logging, access control, lazy loading) | method_missing + respond_to_missing? |
| Share behavior between unrelated classes | a module, see Mixins and Modules and Class Composition |
| Combine interchangeable parts | constructor-injected collaborators |
Start with the smallest public interface you need and forward only those methods. It is easy to add a delegated method later, but taking one away after callers depend on it is hard.