Skip to content
Snippets Groups Projects
Forked from PortalMEC / portalmec
4 commits behind, 14 commits ahead of the upstream repository.
contacts_controller.rb 2.43 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::ContactsController < ApplicationController
  include ::Paginator

  before_action :authenticate_user!, except: [:create]
  before_action :set_contact, only: [:show, :update, :destroy]
	before_action :set_new_contact, only: :index
  before_action :authorize!, except: [:create]

  # GET v1/contacts
  def index
    contacts = paginate policy_scope(Contact)
		render json: contacts
  end

  # GET v1/contacts/1
  def show
    render json: @contact
  end

  # POST v1/contacts
  def create
    @contact = Contact.new(contact_params)
    if @contact.save
      ContactsMailer.new_contact_received(@contact).deliver_now
      render json: @contact, status: :created
    else
      render json: @contact.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT v1/contacts/1
  def update
    if @contact.update(contact_params)
      ContactsMailer.contact_updated(@contact).deliver_now
      render json: @contact
    else
      render json: @contact.errors, status: :unprocessable_entity
    end
  end

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

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_contact
      @contact = Contact.where(id: params[:id]).first

      render status: :not_found if @contact.blank?

      @contact
    end

    # Only allow a trusted parameter "white list" through.
    def contact_params
      params.require(:contact).permit(:name, :email, :message)
    end

    def authorize!
      authorize @contact
    end

		def set_new_contact
			@contact ||= Contact.new
		end
end