parsley/app/models/food.rb

106 lines
1.8 KiB
Ruby
Raw Normal View History

2018-09-12 17:17:15 -05:00
class Food < Ingredient
2016-01-28 14:19:51 -06:00
include TokenizedLike
2016-01-13 17:10:43 -06:00
belongs_to :user
2018-09-11 10:38:07 -05:00
has_many :food_units, inverse_of: :food, dependent: :destroy
2016-07-05 16:31:36 -05:00
2018-09-11 10:38:07 -05:00
accepts_nested_attributes_for :food_units, allow_destroy: true
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
scope :has_density, -> { where.not(density: nil) }
2016-01-28 14:19:51 -06:00
def self.search(query)
tokens = query.to_s.split(' ')
if tokens.empty?
2018-09-11 10:38:07 -05:00
Food.none
2016-01-28 14:19:51 -06:00
else
2018-09-11 10:38:07 -05:00
Food.matches_tokens(:name, tokens)
2016-01-28 14:19:51 -06:00
end
end
def cache_key
if !self.persisted? && self.ndbn.present?
"#{super}/#{self.ndbn}"
else
super
end
end
2018-09-11 10:38:07 -05:00
def custom_units
units = {}
food_units.each do |fu|
units[fu.name] = UnitConversion::parse(fu.gram_weight, "grams")
2016-07-05 16:31:36 -05:00
end
2018-09-11 10:38:07 -05:00
units
end
2018-09-11 22:56:26 -05:00
def nutrition_data
2018-09-11 10:38:07 -05:00
self
end
2016-07-05 16:31:36 -05:00
2018-09-11 22:56:26 -05:00
def nutrition_unit
UnitConversion.parse('100 grams')
end
2016-01-30 15:49:17 -06:00
def ndbn=(value)
@usda_food = nil
super
end
def usda_food
if self.ndbn.present?
@usda_food ||= UsdaFood.find_by_ndbn(self.ndbn)
else
nil
end
end
def usda_food_name
if usda_food
usda_food.long_description
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-06-22 13:49:03 -05:00
copy_fields = [
:water,
:ash,
:protein,
:kcal,
:fiber,
:sugar,
:carbohydrates,
:calcium,
:iron,
:magnesium,
:phosphorus,
:potassium,
:sodium,
:zinc,
:copper,
:manganese,
:vit_c,
:vit_b6,
:vit_b12,
:vit_a,
:vit_e,
:vit_d,
:vit_k,
:cholesterol
]
copy_fields.each do |f|
self.send("#{f}=".to_sym, food.send(f.to_sym))
end
2016-01-24 19:06:26 -06:00
self.lipids = food.lipid
self.density = food.density_best_guess
2016-01-24 17:10:43 -06:00
end
2016-01-12 18:43:00 -06:00
end