Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 3 additions & 26 deletions lib/ipinfo_io.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
39 changes: 39 additions & 0 deletions lib/ipinfo_io/adapter.rb
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions lib/ipinfo_io/response.rb
Original file line number Diff line number Diff line change
@@ -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
Expand Down