class Plate
Attributes
ingredient_quantities[R]
ingredients[R]
name[R]
Public Class Methods
food()
click to toggle source
Getter for the food hash @return [Hash<String, Food>] Hash mapping names to food instances
# File lib/TDD/Plate.rb, line 31 def self.food @@food end
new(name) { |self| ... }
click to toggle source
# File lib/TDD/Plate.rb, line 35 def initialize(name, &block) @name = name @ingredients = [] @ingredient_quantities = [] if block_given? if block.arity == 1 yield self else instance_eval(&block) end end end
Public Instance Methods
add_ingredient(name, quantity)
click to toggle source
# File lib/TDD/Plate.rb, line 49 def add_ingredient(name, quantity) ingredient = @@food[name.strip.downcase] raise( ArgumentError, "Invalid ingredient: #{name}" ) unless !ingredient.nil? # Add the ingredient to the list @ingredients << ingredient # Little convenient lambda to not repeat code below # Given a key of quantity, it checks that the value is Numeric. # If it is numeric, its value times the multiplier is added to # the @ingredient_quantities array check_and_add_amount = ->(key, multiplier = 1.0) { amount = quantity[key] raise( ArgumentError, "Invalid amount type: '#{amount}' must be of type Numeric" ) unless amount.is_a? Numeric @ingredient_quantities << amount * multiplier } # Check what metric is used for the quantity and add if quantity.has_key?(:grams) check_and_add_amount.call(:grams, 1.0) elsif quantity.has_key?(:ounces) check_and_add_amount.call(:ounces, 28.35) elsif quantity.has_key?(:liters) check_and_add_amount.call(:liters, 1.0) elsif quantity.has_key?(:mililiters) check_and_add_amount.call(:mililiters, 1.0 / 1000.0) elsif quantity.has_key?(:portion) # Get the string and convert it to an array value = quantity[:portion].split(" ") # Get the quantity and the string amount = value[0].to_f str = value[1..-1].join(" ").downcase case str when "cup", "cups" amount *= 1.0 when "teaspoon", "teaspoons" amount *= 0.3 when "pinch" amount *= 0.1 when "piece", "pieces" amount *= 1.0 else raise( ArgumentError, "Unknown metric: #{str}" ) end @ingredient_quantities << amount else raise( ArgumentError, "Invalid amount metric in definition of ingredient #{name}" ) end end
method_missing(methodName, *args, &block)
click to toggle source
# File lib/TDD/Plate.rb, line 105 def method_missing(methodName, *args, &block) add_ingredient(*args, &block) end
to_s()
click to toggle source
# File lib/TDD/Plate.rb, line 109 def to_s result = "\n#{@name}\n===\nNutritional composition\n" totalEnergeticValue = 0 @ingredients.length.times do |i| n = @ingredients[i].nutrient_quantities energeticValue = @ingredients[i].energetic_value * @ingredient_quantities[i] totalEnergeticValue += energeticValue result += "#{@ingredients[i].name}\t\t\t#{n[0]}\t#{n[1]}\t#{n[2]}\t#{energeticValue}\n" end result += "total energetic value\t\t\t\t#{totalEnergeticValue}\n" end