class UsdaFoodWeight < ApplicationRecord

  belongs_to :usda_food

  def calculate_density
    return nil if gram_weight.blank? || description.blank? || amount.blank?

    begin
      value_unit = UnitConversion.parse(amount, description)
      if value_unit.volume?
        density_value = gram_weight.to_d / value_unit.raw_value
        density_units = "g/#{value_unit.unit.unit}"
        density = UnitConversion.parse(density_value, density_units)
        return density.convert('oz/cup')
      else
        return nil
      end
    rescue UnitConversion::UnparseableUnitError
      return nil
    end
  end

end
