module Onfleet

Attributes

api_key[RW]
base_url[RW]

Public Class Methods

request(api_url, method, params = {}) click to toggle source
# File lib/onfleet-ruby.rb, line 44
def request(api_url, method, params = {})
  raise(AuthenticationError, 'Set your API Key using Onfleet.api_key = <API_KEY>') unless api_key

  begin
    url = URI.join(base_url, api_url).to_s
    response = RestClient::Request.execute(method: method, url: url, payload: params.to_json, headers: request_headers)
    JSON.parse(response) unless response.empty?
  rescue RestClient::ExceptionWithResponse => e
    if (response_code = e.http_code) && (response_body = e.http_body)
      handle_api_error(response_code, JSON.parse(response_body))
    else
      handle_restclient_error(e)
    end
  rescue RestClient::Exception, Errno::ECONNREFUSED => e
    handle_restclient_error(e)
  end
end

Private Class Methods

encoded_api_key() click to toggle source
# File lib/onfleet-ruby.rb, line 72
def encoded_api_key
  @encoded_api_key ||= Base64.urlsafe_encode64(api_key)
end
handle_api_error(code, body) click to toggle source
# File lib/onfleet-ruby.rb, line 76
def handle_api_error(code, body)
  case code
  when 400, 404
    raise InvalidRequestError, body['message']
  when 401
    raise AuthenticationError, body['message']
  else
    raise OnfleetError, body['message']
  end
end
handle_restclient_error(exception) click to toggle source
# File lib/onfleet-ruby.rb, line 87
def handle_restclient_error(exception)
  message =
    case exception
    when RestClient::RequestTimeout
      'Could not connect to Onfleet. Check your internet connection and try again.'
    when RestClient::ServerBrokeConnection
      'The connetion with onfleet terminated before the request completed. Please try again.'
    else
      'There was a problem connection with Onfleet. Please try again. If the problem persists contact contact@onfleet.com'
    end

  raise ConnectionError, message
end
request_headers() click to toggle source
# File lib/onfleet-ruby.rb, line 64
def request_headers
  {
    Authorization: "Basic #{encoded_api_key}",
    content_type: :json,
    accept: :json
  }
end