Sha256: 090682867d220dc1d243fe08aa529700dc5b872d04946721c068384d6045c157

Contents?: true

Size: 1.62 KB

Versions: 1

Compression:

Stored size: 1.62 KB

Contents

module Geocodable
  class Request
    @ssl_bundle_path = File.dirname(__FILE__) + '/../certs/ca-certificates.crt'

    class << self
      def get(url, params={})
        response = conn.get url, params, headers
        handle_api_error(response) unless response.success?
        response.body
      end

      def headers
        hash = { user_agent: "geocodable-ruby/#{Geocodable::VERSION}" }
        hash[:authorization] = "Bearer #{api_key}" unless api_key.nil?
        hash
      end

      def conn
        Faraday::Response.register_middleware json_parser: JSONParser
        conn = Faraday.new(Geocodable.api_base, ssl: ssl) do |faraday|
          faraday.adapter :excon
          faraday.response :json_parser
        end
      end

      def ssl
        { verify: Geocodable.ssl_verify_certs, ca_file: @ssl_bundle_path }
      end

      def api_key
        Geocodable.api_key
      end

      def handle_api_error(response)
        code, body = response.status, response.body
        begin
          error = body[:errors] || body[:error]
          error = error.first if error.kind_of? Array
        rescue
          raise APIError.new(
            "Invalid response object from API: #{body.inspect}", code, body)
        end

        case code
        when 400, 404 then raise InvalidRequestError.new(error, code, body)
        when 401      then raise AuthenticationError.new(error, code, body)
        when 403      then raise AccessDisabledError.new(error, code, body)
        when 429      then raise OverRequestLimitError.new(error, code, body)
        else
          raise APIError.new(error, code, body)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
geocodable-0.0.1 lib/geocodable/request.rb