Sha256: 39970d3b5d141f5dd871f74ca12b910dda7adf3712d031b6a5d7ff9becb20349

Contents?: true

Size: 926 Bytes

Versions: 2

Compression:

Stored size: 926 Bytes

Contents

# frozen_string_literal: true
require 'faraday'
require 'cgi'

module IPinfo
  class Adapter
    HOST = 'ipinfo.io'

    attr_reader :conn

    def initialize(token = nil, adapter = :net_http)
      @token = token
      @conn = connection(adapter)
    end

    def get(uri)
      @conn.get(uri) do |req|
        default_headers.each_pair do |key, value|
          req.headers[key] = value
        end
        req.params['token'] = CGI::escape(token) if token
      end
    end

    private

    attr_reader :token

    def connection(adapter)
      Faraday.new(url: "https://#{HOST}") do |faraday|
        faraday.adapter adapter
      end
    end

    def default_headers
        headers = {
          'User-Agent' => "IPinfoClient/Ruby/1.0",
          'Accept' => 'application/json'
        }
        if token
          headers['Authorization'] = "Bearer #{CGI::escape(token)}"
        end
        headers
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
IPinfo-0.1.2 lib/ipinfo/adapter.rb
IPinfo-0.1.1 lib/ipinfo/adapter.rb