class RecipeProxy attr_reader :recipe def initialize(recipe) @recipe = recipe parse_yields end def name @recipe.name end def density @density end def density? !self.density.nil? end def get_custom_unit_equivalent(custom_unit_name) unit = @custom_yields.detect { |vu| vu.unit.unit == custom_unit_name } known_unit = @unit_yields.first if unit && known_unit # ex: # custom_unit_name: "rolls" # yields: "3 rolls, 500 g" # desired return: 166.6 g ValueUnit.for(known_unit.value.value / unit.value.value, known_unit.unit) end end private def parse_yields @custom_yields = [] @unit_yields = [] @density = nil @recipe.yields_list.each do |y| begin vu = UnitConversion::parse(yield_string) rescue UnparseableUnitError vu = nil end if vu if vu.unit.nil? @custom_yields << ValueUnit.for(vu.value, 'servings') elsif vu.mass? || vu.volume? @unit_yields << vu else @custom_yields << vu end end end vol = @unit_yields.detect { |u| u.volume? } mas = @unit_yields.detect { |u| u.mass? } # ex # vol: 2 cups # mas: 7 oz if vol && mas @density = "#{mas.value.value / vol.value.value} #{mas.unit.original_unit}/#{vol.unit.original_unit}" end end end