2016-02-14 19:29:34 -06:00
|
|
|
class NutritionData
|
|
|
|
|
2017-04-14 17:06:43 -05:00
|
|
|
NUTRIENTS = {
|
|
|
|
protein: 'g Protein',
|
|
|
|
lipids: 'g Fat',
|
|
|
|
kcal: 'Calories',
|
|
|
|
fiber: 'g Fiber',
|
|
|
|
sugar: 'g Sugar',
|
|
|
|
carbohydrates: 'g Carbohydrates',
|
|
|
|
calcium: nil,
|
|
|
|
iron: nil,
|
|
|
|
magnesium: nil,
|
|
|
|
phosphorus: nil,
|
|
|
|
potassium: nil,
|
|
|
|
sodium: 'mg Sodium',
|
|
|
|
zinc: nil,
|
|
|
|
copper: nil,
|
|
|
|
manganese: nil,
|
|
|
|
vit_c: nil,
|
|
|
|
vit_b6: nil,
|
|
|
|
vit_b12: nil,
|
|
|
|
vit_a: nil,
|
|
|
|
vit_e: nil,
|
|
|
|
vit_d: nil,
|
|
|
|
vit_k: 'µg Vitamin K',
|
|
|
|
cholesterol: nil
|
|
|
|
}
|
2016-06-22 13:49:03 -05:00
|
|
|
|
|
|
|
attr_reader :errors
|
2017-04-14 17:06:43 -05:00
|
|
|
attr_reader *NUTRIENTS.keys
|
2016-02-14 19:29:34 -06:00
|
|
|
|
|
|
|
def initialize(recipe_ingredients)
|
|
|
|
@errors = []
|
2016-06-22 13:49:03 -05:00
|
|
|
|
2017-04-14 17:06:43 -05:00
|
|
|
NUTRIENTS.keys.each do |n|
|
2016-06-22 13:49:03 -05:00
|
|
|
self.instance_variable_set("@#{n}".to_sym, 0.0)
|
|
|
|
end
|
2016-02-14 19:29:34 -06:00
|
|
|
|
|
|
|
recipe_ingredients.each do |i|
|
2018-09-11 22:56:26 -05:00
|
|
|
if i.ingredient.nil? || i.ingredient.nutrition_data.nil?
|
2016-02-14 19:29:34 -06:00
|
|
|
@errors << "#{i.name} has no nutrition data"
|
2018-09-11 22:56:26 -05:00
|
|
|
next
|
|
|
|
end
|
|
|
|
|
|
|
|
nutrient_scale = i.calculate_nutrition_ratio
|
|
|
|
|
|
|
|
if nutrient_scale.nil?
|
|
|
|
@errors << "#{i.name} has an unknown quantity or unit"
|
|
|
|
next
|
|
|
|
end
|
|
|
|
|
|
|
|
unless i.ingredient.nutrition_errors.empty?
|
2018-09-12 17:17:15 -05:00
|
|
|
@errors << "#{i.name}: #{i.ingredient.nutrition_errors.join(", ")}"
|
2016-02-14 19:29:34 -06:00
|
|
|
end
|
|
|
|
|
2017-04-14 17:06:43 -05:00
|
|
|
missing = []
|
2016-02-14 19:29:34 -06:00
|
|
|
|
2017-04-14 17:06:43 -05:00
|
|
|
NUTRIENTS.each do |k, n|
|
2018-09-11 22:56:26 -05:00
|
|
|
value = i.ingredient.nutrition_data.send(k)
|
2016-02-14 19:29:34 -06:00
|
|
|
if value.present?
|
|
|
|
value = value.to_f
|
|
|
|
running_total = self.instance_variable_get("@#{k}".to_sym)
|
2018-09-11 22:56:26 -05:00
|
|
|
delta = value * nutrient_scale
|
2016-02-14 19:29:34 -06:00
|
|
|
self.instance_variable_set("@#{k}".to_sym, running_total + delta)
|
|
|
|
else
|
2017-04-14 17:06:43 -05:00
|
|
|
missing << k
|
2016-02-14 19:29:34 -06:00
|
|
|
end
|
|
|
|
end
|
2017-04-14 17:06:43 -05:00
|
|
|
|
|
|
|
missing = missing.map { |k| NUTRIENTS[k] }.compact
|
|
|
|
unless missing.empty?
|
|
|
|
@errors << "#{i.name} missing the following nutrients: #{missing.join(', ')}"
|
|
|
|
end
|
2016-02-14 19:29:34 -06:00
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|