Skip to content
Snippets Groups Projects
Forked from PortalMEC / portalmec
4 commits behind, 42 commits ahead of the upstream repository.
requirements_controller.rb 2.40 KiB

# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with portalmec.  If not, see <http://www.gnu.org/licenses/>.

class V1::RequirementsController < ApplicationController
  include ::Paginator

  before_action :set_requirement, only: [:show, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]
  before_action :authorize!, only: [:update, :destroy]

	def index
    requirements = paginate Requirement
		render json: requirements
	end

	def show
    render json: @requirement
	end

  def create
    @requirement = Requirement.new(requirement_params)
    authorize @requirement

    if @requirement.save
      @requirement.add_achievements(extra_params[:achievements])
      render json: @requirement, status: :created
    else
      render json: @requirement.errors, status: :unprocessable_entity
    end
  end

  # PUT/PATCH /v1/requirements/1
  def update
    if @requirement.update(requirement_params)
      @requirement.update_achievements(extra_params[:achievements])
      render json: @requirement, status: :ok
    else
      render json: @requirement.errors, status: :unprocessable_entity
    end
  end

  # DELETE /v1/requirements/1
  def destroy
    @requirement.destroy
    response = { 'status': 'deleted' }
    render status: :ok, json: response
  end

  private

  def set_requirement
    @requirement ||= Requirement.find_by_id(params[:id])
    if @requirement.blank?
      render status: :not_found
    end
  end

  def requirement_params
    params.require(:requirement).permit(:description, :goal, :repeatable, :action_id)
  end

  def extra_params
    return {} if params[:requirement].nil?
    params[:requirement].permit(achievements: [])
  end

  def authorize!
    authorize @requirement
  end
end