diff --git a/lib/ipinfo_io.rb b/lib/ipinfo_io.rb index 84d7608..cae2414 100644 --- a/lib/ipinfo_io.rb +++ b/lib/ipinfo_io.rb @@ -3,43 +3,20 @@ require "ipinfo_io/version" require 'ipinfo_io/errors' require 'ipinfo_io/response' -require 'faraday' -require 'json' +require 'ipinfo_io/adapter' module IpinfoIo RATE_LIMIT_MESSAGE = "To increase your limits, please review our paid plans at https://ipinfo.io/pricing" - HOST = 'ipinfo.io' class << self attr_accessor :access_token def lookup(ip=nil) - response = Faraday.get(url_builder(ip)) do |req| - default_headers.each_pair do |key, value| - req.headers[key] = value - end - end + response = Adapter.new(access_token).get(ip) raise RateLimitError.new(RATE_LIMIT_MESSAGE) if response.status.eql?(429) - IpinfoIo::Response.from_faraday(response) - end - - private - - def url_builder(ip) - if access_token - "https://#{HOST}/#{ip}?token=#{access_token}" - else - "https://#{HOST}/#{ip}" - end - end - - def default_headers - { - 'User-Agent' => "ruby/#{::IpinfoIo::VERSION}", - 'Accept' => 'application/json' - } + Response.from_faraday(response) end end end diff --git a/lib/ipinfo_io/adapter.rb b/lib/ipinfo_io/adapter.rb new file mode 100644 index 0000000..87f0b80 --- /dev/null +++ b/lib/ipinfo_io/adapter.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true +require 'faraday' + +module IpinfoIo + class Adapter + HOST = 'ipinfo.io' + + def initialize(token=nil) + @token = token + end + + def get(ip=nil) + Faraday.get(url_builder(ip)) do |req| + default_headers.each_pair do |key, value| + req.headers[key] = value + end + end + end + + private + + attr_reader :token + + def url_builder(ip) + if token + "https://#{HOST}/#{ip}?token=#{token}" + else + "https://#{HOST}/#{ip}" + end + end + + def default_headers + { + 'User-Agent' => "ruby/#{::IpinfoIo::VERSION}", + 'Accept' => 'application/json' + } + end + end +end diff --git a/lib/ipinfo_io/response.rb b/lib/ipinfo_io/response.rb index 1182086..1308908 100644 --- a/lib/ipinfo_io/response.rb +++ b/lib/ipinfo_io/response.rb @@ -1,3 +1,6 @@ +# frozen_string_literal: true +require 'json' + module IpinfoIo class Response # The data contained by the HTTP body of the response deserialized from