parsley/app/models/ingredient.rb

52 lines
1.3 KiB
Ruby
Raw Normal View History

2016-01-12 18:43:00 -06:00
class Ingredient < ActiveRecord::Base
2016-01-28 14:19:51 -06:00
include TokenizedLike
2016-01-13 17:10:43 -06:00
validates :name, presence: true
2016-01-14 15:22:15 -06:00
validates :density, density: true, allow_blank: true
2016-01-13 17:10:43 -06:00
2016-01-28 14:19:51 -06:00
def self.search(query)
tokens = query.to_s.split(' ')
if tokens.empty?
Ingredient.none
else
Ingredient.matches_tokens(:name, tokens)
end
end
2016-01-24 17:10:43 -06:00
def set_usda_food(food)
2016-01-28 14:19:51 -06:00
return unless food
2016-01-24 17:10:43 -06:00
self.ndbn = food.ndbn
2016-01-24 19:06:26 -06:00
self.water = food.water
self.protein = food.protein
self.lipids = food.lipid
self.ash = food.ash
self.kcal = food.kcal
self.fiber = food.fiber
self.sugar = food.sugar
2016-01-24 17:10:43 -06:00
self.density = calculate_density(food.gram_weight_1, food.gram_weight_desc_1) || calculate_density(food.gram_weight_2, food.gram_weight_desc_2)
end
def calculate_density(grams, description)
return nil if grams.blank? || description.blank?
# replace 'fl oz' with 'floz'
description = description.gsub(/fl oz/i, 'floz')
begin
unit = UnitConversion.parse(description)
if UnitConversion.volume?(unit)
mass = Unitwise(grams, 'g')
density = (mass / unit).convert_to(UnitConversion.normalize_unit_names('oz/cup'))
return "#{density.value.round(4)} oz/cup"
else
return nil
end
rescue UnitConversion::UnparseableUnitError
return nil
end
end
2016-01-12 18:43:00 -06:00
end