Skip to content

Instantly share code, notes, and snippets.

@manveru
Created August 2, 2010 02:40
Show Gist options
  • Save manveru/504042 to your computer and use it in GitHub Desktop.
Save manveru/504042 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
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment