Class: Zippopotamus::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/zippopotamus/client.rb

Instance Method Summary collapse

Constructor Details

#initialize(use_persistent_connection = false) ⇒ Client

Returns a new instance of Client.



9
10
11
# File 'lib/zippopotamus/client.rb', line 9

def initialize(use_persistent_connection = false)
  @connection = Excon.new('http://api.zippopotam.us', persistent: use_persistent_connection)
end

Instance Method Details

#lookup_postcode(postcode, country = 'us') ⇒ Object

Parameters:

  • postcode (String)
  • country (String) (defaults to: 'us')

    2 letter country code (default: ‘us’)



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/zippopotamus/client.rb', line 17

def lookup_postcode(postcode, country = 'us')
  postcode = postcode.to_s if postcode.is_a?(Integer)
  raise "Invalid postcode parameter: '#{postcode}'" if not_blank_string?(postcode)
  raise "Invalid country parameter: '#{country}'" if not_blank_string?(country) || country.length != 2
  country = country.downcase
  begin
    r = @connection.get(path: "/#{country}/#{postcode}")
  rescue Excon::Errors::SocketError
    # just retry
    r = @connection.get(path: "/#{country}/#{postcode}")
  end
  if r.status == 200
    return Place.new(postcode, *JSON.parse(r.body)['places'])
  else
    return nil
  end
end