Class: CraftyClicks::ApiBase

Inherits:
Object
  • Object
show all
Defined in:
lib/crafty_clicks/api_base.rb,
lib/crafty_clicks/api_base/exceptions.rb

Defined Under Namespace

Classes: Exceptions

Constant Summary collapse

ADDRESS_ENDPOINT =
'https://api.craftyclicks.co.uk/address/1.1'
POSTCODE_ENDPOINT =
'http://pcls1.craftyclicks.co.uk/json'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(product:, service:, params: {}, http_method: :get) ⇒ ApiBase

Returns a new instance of ApiBase.



12
13
14
15
16
17
# File 'lib/crafty_clicks/api_base.rb', line 12

def initialize(product:, service:, params: {}, http_method: :get)
  @product = self.class.const_get("#{product.upcase}_ENDPOINT")
  @service = service
  @params = params.merge(key: CraftyClicks.configuration.api_key)
  @http_method = http_method
end

Instance Attribute Details

#resultObject

Returns the value of attribute result.



8
9
10
# File 'lib/crafty_clicks/api_base.rb', line 8

def result
  @result
end

Instance Method Details

#perform_requestObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/crafty_clicks/api_base.rb', line 19

def perform_request
  process_result(
    RestClient::Request.execute(
      method: @http_method,
      url: "#{@product}/#{@service}",
      payload: @params.to_json,
      headers: { content_type: :json, accept: :json }
    )
  )
rescue RestClient::Unauthorized, RestClient::Forbidden, RestClient::ResourceNotFound => e
  raise Exceptions::ApiError.new(e.response), "Unauthorized: #{e.response}"
rescue RestClient::InternalServerError => e
  raise Exceptions::ApiError.new(e.response), "Server error: #{e.response}"
end