forked from propublica/qis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
goog_geocoder.rb
39 lines (32 loc) · 922 Bytes
/
goog_geocoder.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
require 'uri'
require 'net/http'
require 'base64'
require 'openssl'
require 'json'
class GoogGeocoder
CLIENT_ID = ::CREDENTIALS['google_client_id']
KEY = ::CREDENTIALS['google_key']
PATH = CLIENT_ID && KEY ? "/maps/api/geocode/json?sensor=false&client=#{CLIENT_ID}" : "/maps/api/geocode/json?sensor=false"
def initialize(address)
@address = address
@path = "#{PATH}&address=#{URI.encode @address}"
geocode!
end
def resp
JSON.parse @resp
end
private
def geocode!
if CLIENT_ID
sign!
@resp = Net::HTTP.get("maps.googleapis.com", "#{@path}&signature=#{@key}")
else
@resp = Net::HTTP.get("maps.googleapis.com", "#{@path}")
end
end
def sign!
signer = OpenSSL::Digest::Digest.new('sha1')
digest = OpenSSL::HMAC.digest(signer, Base64.decode64(KEY.tr('-_','+/')), @path)
@key = Base64.encode64(digest).tr('+/','-_').strip
end
end