Skip to content

Instantly share code, notes, and snippets.

@henrik
Created February 24, 2012 13:04
Show Gist options
  • Save henrik/1900793 to your computer and use it in GitHub Desktop.
Save henrik/1900793 to your computer and use it in GitHub Desktop.
Forwarding for Ruby composition.
# By Barsoom AB <http://barsoom.se> 2012-02-24 under the MIT license.
require 'active_support/core_ext'
module Forwarding
def forward(name, opts)
klass = opts[:to]
define_method(name) do
@forwards ||= {}
@forwards[name] ||= klass.new(self)
end
if delegations = opts[:delegate]
delegate *delegations, :to => name
end
end
end
class Customer
extend Forwarding
class Naming < Struct.new(:customer)
def name
"Pelle"
end
def id_and_name
"#{customer.id}. Pelle"
end
end
class Timing < Struct.new(:customer)
def age
42
end
def birthday
"Today!"
end
end
forward :naming, to: Naming,
delegate: :name
forward :times, to: Timing,
delegate: [:birthday, :age]
def id
123
end
end
p Customer.new.name
p Customer.new.naming.name
p Customer.new.naming.id_and_name
p Customer.new.age
p Customer.new.birthday
p Customer.new.times.birthday
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment