class Recipe < ApplicationRecord include TokenizedLike has_many :recipe_ingredients, -> { order :sort_order }, inverse_of: :recipe, dependent: :destroy has_many :recipe_steps, -> { order :sort_order }, inverse_of: :recipe, dependent: :destroy belongs_to :user has_and_belongs_to_many :tags scope :undeleted, -> { where('deleted <> ? OR deleted IS NULL', true) } scope :not_log, -> { where('is_log <> ? OR is_log IS NULL', true) } scope :active, -> { undeleted.not_log } accepts_nested_attributes_for :recipe_ingredients, allow_destroy: true accepts_nested_attributes_for :recipe_steps, allow_destroy: true validates :name, presence: true validates :total_time, numericality: true, allow_blank: true validates :active_time, numericality: true, allow_blank: true def scale(factor, auto_unit = false) recipe_ingredients.each do |ri| ri.scale(factor, auto_unit) end end def convert_to_metric recipe_ingredients.each do |ri| ri.to_metric end end def convert_to_standard recipe_ingredients.each do |ri| ri.to_standard end end def convert_to_mass recipe_ingredients.each do |ri| ri.to_mass end end def convert_to_volume recipe_ingredients.each do |ri| ri.to_volume end end def tag_names self.tags.map { |t| t.name } end def tag_names=(names) names = Array.wrap(names).map { |n| n.to_s }.select { |n| n.length > 0 } existing_tags = Tag.by_name(names) new_tags = names.select { |n| existing_tags.none? { |t| t.is?(n) } } self.tags = existing_tags new_tags.each do |n| self.tags << Tag.new(name: n) end end def nutrition_data(recalculate = false) if recalculate || @nutrition_data.nil? @nutrition_data = calculate_nutrition_data end @nutrition_data end def parsed_yield if @parsed_yield.nil? && self.yields.present? @parsed_yield = YieldParser.parse(self.yields) end @parsed_yield end def update_rating! self.rating = Log.for_recipe(self).for_user(self.user_id).where('rating IS NOT NULL').average(:rating) save(validate: false) end # Creates a copy of this recipe suitable for associating to a log def log_copy(user) copy = Recipe.new copy.user = user copy.is_log = true copy.name = self.name copy.description = self.description copy.source = self.source copy.yields = self.yields copy.total_time = self.total_time copy.active_time = self.active_time self.recipe_ingredients.each do |ri| copy.recipe_ingredients << ri.log_copy end self.recipe_steps.each do |rs| copy.recipe_steps << rs.log_copy end copy end def self.for_criteria(criteria) query = active.order(criteria.sort_column => criteria.sort_direction).page(criteria.page).per(criteria.per) if criteria.name.present? query = query.matches_token(:name, criteria.name) end if criteria.tags.present? tags = Tag.by_name(criteria.tags.split) query = query.where(id: tags.joins(:recipes).pluck('recipes.id')) end query end private def calculate_nutrition_data NutritionData.new(recipe_ingredients) end end