parsley/app/controllers/recipes_controller.rb
2018-09-12 17:17:15 -05:00

96 lines
2.5 KiB
Ruby

class RecipesController < ApplicationController
before_action :set_recipe, only: [:show, :edit, :update, :destroy]
before_action :ensure_valid_user, except: [:show, :scale, :index]
# GET /recipes
def index
@criteria = ViewModels::RecipeCriteria.new(criteria_params)
@recipes = Recipe.for_criteria(@criteria).includes(:tags)
end
# GET /recipes/1
# GET /recipes/1.json
def show
if params[:scale].present?
@scale = params[:scale]
@recipe.scale(params[:scale], true)
end
if params[:system].present?
@system = params[:system]
case @system
when 'metric'
@recipe.convert_to_metric
when 'standard'
@recipe.convert_to_standard
end
end
if params[:unit].present?
@unit = params[:unit]
case @unit
when 'mass'
@recipe.convert_to_mass
when 'volume'
@recipe.convert_to_volume
end
end
end
# POST /recipes
def create
@recipe = Recipe.new(recipe_params)
@recipe.user = current_user
if @recipe.save
render json: { success: true }
else
render json: @recipe.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /recipes/1
def update
ensure_owner(@recipe) do
if @recipe.update(recipe_params)
render json: { success: true }
else
render json: @recipe.errors, status: :unprocessable_entity
end
end
end
# POST /recipes/preview_steps
def preview_steps
render json: { rendered_steps: MarkdownProcessor.render(params[:step_text]) }
end
# DELETE /recipes/1
def destroy
ensure_owner(@recipe) do
@recipe.deleted = true
@recipe.save!(validate: false)
render json: { success: true }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_recipe
@recipe = Recipe.includes(recipe_ingredients: [{food: :food_units }, {recipe_as_ingredient: {recipe_ingredients: {food: :food_units }}}]).find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def recipe_params
params.require(:recipe).permit(:name, :description, :source, :yields, :total_time, :active_time, :step_text, :is_ingredient, tag_names: [], recipe_ingredients_attributes: [:name, :ingredient_id, :quantity, :units, :preparation, :sort_order, :id, :_destroy])
end
def criteria_params
params.require(:criteria).permit(*ViewModels::RecipeCriteria::PARAMS)
end
end