Skip to content

Instantly share code, notes, and snippets.

@JulesWang
Created October 7, 2011 08:55
Show Gist options
  • Save JulesWang/1269820 to your computer and use it in GitHub Desktop.
Save JulesWang/1269820 to your computer and use it in GitHub Desktop.
module Decorator
def initialize(decorated)
@decorated = decorated
end
def method_missing(method,*args)
# empty? is a method; ?: is a tri-operator
args.empty? ? @decorated.send(method):@decorated.send(method,args)
end
# Decorator does not change the nature of object it decorates;
def kind_of?(name)
@decorated.kind_of?name
end
end
class Coffee
def cost
2
end
def taste
p "taste good!"
end
end
class Milk
include Decorator
def cost
@decorated.cost+0.4
end
end
class Whip
include Decorator
def cost
@decorated.cost+0.2
end
end
my_coffee = Whip.new(Milk.new(Coffee.new))
p my_coffee.cost;
p my_coffee.kind_of?Coffee
my_coffee.taste
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment