class Tikkie::Api::V1::Responses::Base

Base class for all responses.

Attributes

data[R]
response[R]

Public Class Methods

new(response) click to toggle source
# File lib/tikkie/api/v1/responses/base.rb, line 13
def initialize(response)
  if response.respond_to?(:body)
    @response = response
    @data = parse_body(response.body)
  else
    @data = response
  end
end

Public Instance Methods

error?() click to toggle source
# File lib/tikkie/api/v1/responses/base.rb, line 30
def error?
  !success?
end
errors() click to toggle source
# File lib/tikkie/api/v1/responses/base.rb, line 38
def errors
  @errors ||= begin
    errors = []

    if data[:errors]
      data[:errors].each do |error|
        errors << Tikkie::Api::V1::Responses::Error.new(error)
      end
    end

    errors
  end
end
response_code() click to toggle source
# File lib/tikkie/api/v1/responses/base.rb, line 22
def response_code
  response.code.to_i if response
end
success?() click to toggle source
# File lib/tikkie/api/v1/responses/base.rb, line 26
def success?
  (response_code == 200 || response_code == 201) && !@invalid
end
trace_id() click to toggle source
# File lib/tikkie/api/v1/responses/base.rb, line 34
def trace_id
  response["Trace-Id"] if response
end

Private Instance Methods

parse_body(body) click to toggle source
# File lib/tikkie/api/v1/responses/base.rb, line 54
def parse_body(body)
  body = body.respond_to?(:read) ? body.read : body

  JSON.parse(body, symbolize_names: true)
rescue JSON::ParserError => ex
  @invalid = true

  {
    message: "Unable to parse JSON: #{ex.message}"
  }
end