53 lines
1.3 KiB
Ruby
53 lines
1.3 KiB
Ruby
class RecipeIngredient < ActiveRecord::Base
|
|
|
|
belongs_to :ingredient
|
|
belongs_to :recipe, inverse_of: :recipe_ingredients
|
|
|
|
validates :sort_order, presence: true
|
|
|
|
def name
|
|
if self.ingredient_id.present?
|
|
self.ingredient.name
|
|
else
|
|
super
|
|
end
|
|
end
|
|
|
|
def display_name
|
|
str = [quantity, units, name].delete_if { |i| i.blank? }.join(' ')
|
|
str << ", #{preparation}" if preparation.present?
|
|
str
|
|
end
|
|
|
|
def scale(factor, auto_unit = false)
|
|
if factor.present? && self.quantity.present? && factor != '1'
|
|
|
|
value_unit = UnitConversion.parse(self.quantity, self.units)
|
|
value_unit = value_unit.scale(factor)
|
|
|
|
if auto_unit
|
|
value_unit = value_unit.auto_unit
|
|
end
|
|
|
|
self.quantity = value_unit.pretty_value
|
|
self.units = value_unit.unit.to_s
|
|
end
|
|
end
|
|
|
|
def can_convert_to_grams?
|
|
if self.quantity.present? && self.units.present?
|
|
value_unit = UnitConversion.parse(self.quantity, self.units)
|
|
value_unit.mass? || (value_unit.volume? && self.ingredient && self.ingredient.density.present?)
|
|
else
|
|
false
|
|
end
|
|
end
|
|
|
|
def to_grams
|
|
value_unit = UnitConversion.parse(self.quantity, self.units)
|
|
gram_unit = value_unit.convert('g', self.ingredient ? self.ingredient.density : nil)
|
|
gram_unit.raw_value
|
|
end
|
|
|
|
end
|