123456789_123456789_123456789_123456789_123456789_

Class: Timezone::Lookup::Google

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, Basic
Instance Chain:
self, Basic
Inherits: Timezone::Lookup::Basic
Defined in: lib/timezone/lookup/google.rb

Constant Summary

Class Method Summary

Basic - Inherited

Instance Attribute Summary

Basic - Inherited

Instance Method Summary

Basic - Inherited

#client

Returns an instance of the request handler.

#lookup

Returns a timezone name for a given lat, long pair.

Constructor Details

.new(config) ⇒ Google

[ GitHub ]

  
# File 'lib/timezone/lookup/google.rb', line 19

def initialize(config)
  if config.api_key.nil?
    raise(::Timezone::Error::InvalidConfig, 'missing api key')
  end

  config.protocol ||= 'https'
  config.url ||= 'maps.googleapis.com'

  super
end

Instance Attribute Details

#use_google_enterprise?Boolean (readonly, private)

[ GitHub ]

  
# File 'lib/timezone/lookup/google.rb', line 54

def use_google_enterprise?
  !config.client_id.nil?
end

Instance Method Details

#authorize(url) (private)

[ GitHub ]

  
# File 'lib/timezone/lookup/google.rb', line 58

def authorize(url)
  if use_google_enterprise?
    url += "&client=#{CGI.escape(config.client_id)}"

    sha1 = OpenSSL::Digest.new('sha1')
    binary_key = Base64.decode64(config.api_key.tr('-_', '+/'))
    binary_signature = OpenSSL::HMAC.digest(sha1, binary_key, url)
    signature = Base64.encode64(binary_signature).tr('+/', '-_').strip

    url + "&signature=#{signature}"
  else
    url + "&key=#{config.api_key}"
  end
end

#lookup(lat, long)

[ GitHub ]

  
# File 'lib/timezone/lookup/google.rb', line 30

def lookup(lat, long)
  response = client.get(url(lat, long))

  if response.code == '403'
    raise(Timezone::Error::Google, '403 Forbidden')
  end

  return unless /^2\d\d$/.match?(response.code)

  data = JSON.parse(response.body)

  return if data['status'] == NO_TIMEZONE_INFORMATION

  if data['status'] != 'OK'
    raise(Timezone::Error::Google, data['errorMessage'])
  end

  data['timeZoneId']
rescue StandardError => e
  raise(Timezone::Error::Google, e.message)
end

#url(lat, long) (private)

[ GitHub ]

  
# File 'lib/timezone/lookup/google.rb', line 73

def url(lat, long)
  query = URI.encode_www_form(
    'location' => "#{lat},#{long}",
    'timestamp' => Time.now.to_i
  )

  authorize("/maps/api/timezone/json?#{query}")
end