class GoCardless::Response

A class to wrap an API response

Public Class Methods

new(response) click to toggle source

Initialize a response instance @param response an API response

# File lib/gocardless-pro/response.rb, line 6
def initialize(response)
  @response = response
end

Public Instance Methods

body() click to toggle source

Return the body of the API response

# File lib/gocardless-pro/response.rb, line 11
def body
  json? ? handle_json : handle_raw
end
error?() click to toggle source

Returns true if the response is an error

# File lib/gocardless-pro/response.rb, line 23
def error?
  @response.status >= 400
end
json?() click to toggle source

Returns true if the response is JSON

# File lib/gocardless-pro/response.rb, line 16
def json?
  content_type = @response.headers['Content-Type'] ||
                 @response.headers['content-type'] || ''
  content_type.include?('application/json')
end
limit() click to toggle source

Returns the limit parameter from the response

# File lib/gocardless-pro/response.rb, line 35
def limit
  meta.fetch('limit', nil)
end
meta() click to toggle source

Returns the meta hash of the response

# File lib/gocardless-pro/response.rb, line 28
def meta
  fail ResponseError, 'Cannot fetch meta for non JSON response' unless json?

  json_body.fetch('meta', {})
end

Private Instance Methods

error_class_for_type(type) click to toggle source
# File lib/gocardless-pro/response.rb, line 58
def error_class_for_type(type)
  {
    validation_failed: GoCardless::ValidationError,
    gocardless: GoCardless::GoCardlessError,
    invalid_api_usage: GoCardless::InvalidApiUsageError,
    invalid_state: GoCardless::InvalidStateError
  }.fetch(type.to_sym)
end
handle_json() click to toggle source
# File lib/gocardless-pro/response.rb, line 49
def handle_json
  if error?
    type = json_body['error']['type']
    fail(error_class_for_type(type), json_body['error'])
  else
    json_body
  end
end
handle_raw() click to toggle source
# File lib/gocardless-pro/response.rb, line 67
def handle_raw
  default_raw_message = {
    'message' => "Something went wrong with this raw request\n" \
    "status: #{@response.status}\n" \
    "headers: #{@response.headers}\n" \
    "body: #{@response.body}"
  }
  error? ? fail(ApiError, default_raw_message) : raw_body
end
json_body() click to toggle source
# File lib/gocardless-pro/response.rb, line 41
def json_body
  @json_body ||= JSON.parse(@response.body)
end
raw_body() click to toggle source
# File lib/gocardless-pro/response.rb, line 45
def raw_body
  @response.body
end