Skip to content

Instantly share code, notes, and snippets.

@rickhull
Created August 2, 2010 02:14
Show Gist options
  • Save rickhull/504024 to your computer and use it in GitHub Desktop.
Save rickhull/504024 to your computer and use it in GitHub Desktop.
# example of delegate pattern, using a car analogy
# e.g. the car delegates to engine
# . ask the car to speed up, and the car will ask the engine to speed up
#
class Car
def initialize(majors)
@engine = Engine.new
end
def method_missing(meth, *args)
@engine.respond_to?(meth) ? @engine.send(meth, *args) : super
end
def respond_to?(meth)
super || @engine.respond_to?(meth)
end
end
# now, let's say the car delegates to the chassis as well
# e.g. ask the car to get softer, and the car will ask the chassis to get softer
#
class Car
delegate_to :engine
delegate_to :chassis
def initialize
@engine = Engine.new
@chassis = Chassis.new
end
end
# so, how do we write delegate_to?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment