Skip to content

Instantly share code, notes, and snippets.

@rickhull
Forked from manveru/delegation.rb
Created August 2, 2010 02:51
Show Gist options
  • Save rickhull/504047 to your computer and use it in GitHub Desktop.
Save rickhull/504047 to your computer and use it in GitHub Desktop.
module Delegator
def self.extended(into)
(class << into; self; end).send :attr_accessor, :delegates
into.delegates = []
into.send :define_method, :method_missing do |method, *args, &block|
self.class.delegates.map{|delegate| send(delegate) }.each do |receiver|
next unless receiver.respond_to?(method)
return receiver.send(method, *args, &block)
end
super
end
end
def delegate_to(*names)
@delegates |= names
end
end
# e.g.
if __FILE__ == $0
class Engine
def speed_up
puts "Go Go Engine Speed Up!"
end
end
class Chassis
def transform
puts "Go Go Chassis transformation!"
end
end
class Car
extend Delegator
delegate_to :engine, :chassis
attr_reader :engine, :chassis
def initialize
@engine = Engine.new
@chassis = Chassis.new
end
end
car = Car.new
car.speed_up
car.transform
end
###################
# output
ruby delegation.rb
Go Go Engine Speed Up!
delegation.rb:9:in `method_missing': unexpected return (LocalJumpError)
from delegation.rb:7:in `each'
from delegation.rb:7:in `method_missing'
from delegation.rb:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment