summaryrefslogtreecommitdiff
path: root/app/controllers/api/companies_controller.rb
blob: 4c19716922cf32286682340db046fbc70121b186 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# frozen_string_literal: true

module Api
  # CompaniesController
  class CompaniesController < MasterController
    def index
      @companies = Company.all

      render json: serialized_collection.serializable_hash, status: 200
    end

    def show
      @company = Company.find_by(short_name: params[:id])

      render json: serialized_object.serializable_hash, status: :ok and return if @company

      render status: :not_found
    end

    def create
      @company = Company.new(permitted_params)

      render json: serialized_object.serializable_hash, status: :ok and return if @company.save

      render json: { errors: @company.errors.as_json }, status: :unprocessable_entity
    end

    def update
      @company = Company.find_by(short_name: params[:id])

      render status: :not_found and return if @company.nil?

      if @company.update(permitted_params)
        render json: serialized_object.serializable_hash, status: :ok
      else
        render json: { errors: @company.errors.as_json }, status: :unprocessable_entity
      end
    end

    private

    def serialized_object
      CompanySerializer.new(@company)
    end

    def serialized_collection
      CompanySerializer.new(@companies.includes(logo_attachment: :blob).page(params[:page]))
    end

    def permitted_params
      params.permit(:name, :country, :short_name, :logo)
    end
  end
end