29 Jul '16, 9am

Evaluating Alternative Decorator Implementations In Ruby

module Decorator def initialize(component) @component = component end def method_missing(meth, *args) if @component.respond_to?(meth) @component.send(meth, *args) else super end end def respond_to?(meth) @component.respond_to?(meth) end end class Coffee def cost 2 end def origin "Colombia" end end class Milk include Decorator def cost @component.cost + 0.4 end end coffee = Coffee.new Sugar.new(Milk.new(coffee)).cost # 2.6 Sugar.new(Sugar.new(coffee)).cost # 2.4 Sugar.new(Milk.new(coffee)).origin # Colombia Sugar.new(Milk.new(coffee)).class # Sugar

Full article: https://robots.thoughtbot.com/evaluating-alternative-deco...

Tweets

Light Decorator Pattern

rubyflow.com 31 Jul '16, 2pm

× The Ruby and Rails community linklog Made a library? Written a blog post? Found a useful tutorial? Share it with the Rub...