Created
August 2, 2010 02:40
-
-
Save manveru/504042 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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