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) @criteria.page = params[:page] @criteria.per = params[:per] @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: {ingredient: :ingredient_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, 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