summaryrefslogtreecommitdiff
path: root/app/controllers/api/cards_controller.rb
blob: 58110c66fb45be7b2fbeb2c2ef1264afafa766df (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# frozen_string_literal: true

module Api
  # CardsController
  # Or, the payment method's controller.
  class CardsController < AuthenticatedController
    def index
      @cards = current_user_account.cards

      render json: serialized_collection.serializable_hash, status: :ok
    end
    
    def show
      @card = current_user_account.cards.find_by(id: params[:id])
      
      if @card
      	render json: serialized_object.serializable_hash, status: :ok
      else
      	render status: :not_found
      end
    end

    def create
      @card = current_user_account.cards.new(permitted_params)

      if @card.save
        render json: serialized_object.serializable_hash, status: :ok
      else
        render json: { errors: @card.errors.as_json }, status: :unprocessable_entity
      end
    end

    def update
      @card = Card.find_by(id: params[:id])

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

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

    def destroy
      @card = Card.find_by(id: params[:id])

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

      @card.destroy

      render status: :no_content
    end

    private

    def serialized_collection
      CardSerializer.new(@cards)
    end

    def serialized_object
      CardSerializer.new(@card)
    end

    def permitted_params
      params.permit(:number, :expiration_year, :expiration_month, :expiration_day, :security_code)
    end
  end
end