Sha256: ca525bc41acf65bb73e391b0ffc97431ef62c18a7d740ac0cb28d5ef9123fa84

Contents?: true

Size: 1.32 KB

Versions: 1

Compression:

Stored size: 1.32 KB

Contents

# frozen_string_literal: true

module JSONAPIHelpers
  module Serializers
    class Error
      attr_reader :status, :detail, :code

      def initialize(
        detail:,
        status: 422,
        code: nil,
        pointer: nil,
        attribute: nil,
        key_transform: JSONAPIHelpers.config.key_transform
      )
        @status = status
        @detail = detail
        @pointer = pointer(
          pointer: pointer,
          attribute: attribute,
          key_transform: key_transform
        )
        @code = code
      end

      def to_h
        response = { status: @status, detail: @detail }
        response[:code] = @code unless @code.nil?
        response.merge!(@pointer)
      end

      private

      def pointer(pointer:, attribute:, key_transform:)
        return {} if pointer.nil? && attribute.nil?

        full_pointer = if pointer
                         pointer
                       else
                         attribute_pointer(attribute, key_transform: key_transform)
                       end
        {
          source: {
            pointer: full_pointer
          }
        }
      end

      def attribute_pointer(attribute, key_transform:)
        attribute_name = KeyTransform.call(attribute.to_s, key_transform: key_transform)
        "/data/attributes/#{attribute_name}"
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
jsonapi_helpers-0.2.0 lib/jsonapi_helpers/serializers/error.rb