使用Ruby在对象组合中建模cookie

时间:2014-06-10 04:46:05

标签: ruby oop inheritance

我是一位新的Rubyist,我想知道如何从个别cookie中访问成分类?众所周知,饼干是由不同的成分制成的。如何在不设置默认值的情况下为单个cookie指定默认成分?即使我有默认值,我如何更新这些值以反映最新的“配方”?拜托,谢谢!

#Cookie Factory   

module CookieFactory
  def self.create(args) 
    cookie_batch = []
    args.each do |cookie|
      cookie_batch << PeanutButter.new if cookie == "peanut butter"
      cookie_batch << ChocholateChip.new if cookie == "chocolate chip"
      cookie_batch << Sugar.new if cookie == "sugar"
    end
    return cookie_batch
  end
end

#Classes/Subclasses 

class Ingredients
  attr_reader 
  def initialize(contents = {})
    # contents = defaults.merge(contents)
    @sugar = contents.fetch(:sugar, "1.5 cups")
    @salt = contents.fetch(:salt, "1 teaspoon")
    @gluten = contents.fetch(:gluten, "0")
    @cinnamon = contents.fetch(:cinnamon, "0.5 teaspoon")
  end
end

class Cookie 
  attr_reader :status, :ingredients

  def initialize(ingredients = {})
    @ingredients = ingredients
    @status = :doughy
    super()
  end

  def bake!
    @status = :baked
  end

end

class PeanutButter < Cookie
  attr_reader :peanut_count
  def initialize
    @peanut_count = 100
    super()
  end 

  def defaults
    {
      :peanut_shells => 5
    }
  end
end

class Sugar < Cookie
  attr_reader :sugar
  def initialize
    @sugar = "1_cup"
    super()
  end
end

class ChocholateChip < Cookie
  attr_reader :choc_chip_count
  def initialize
    @choc_chip_count = 200
    super()
  end
end

1 个答案:

答案 0 :(得分:0)

您可以使用Hash#merge来实现此行为:

class PeanutButter < Cookie
  attr_reader :peanut_count
  def initialize(ingredients)
    @peanut_count = 100
    super(ingredients.merge(defaults))
  end 

  def defaults
    {
      :peanut_shells => 5
    }
  end
end