123456789_123456789_123456789_123456789_123456789_

Class: Timezone::Lookup::Geonames

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/geonames.rb

Constant Summary

  • NO_TIMEZONE_INFORMATION =

    Status code used by GeoNames to indicate that the lookup succeeded, but there is no timezone information for the given <lat, lng>. This can happen if the <lat, lng> resolves to a point in the middle of the ocean, for example.

    # File 'lib/timezone/lookup/geonames.rb', line 16
    15

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) ⇒ Geonames

[ GitHub ]

  
# File 'lib/timezone/lookup/geonames.rb', line 18

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

  config.protocol ||= 'http'
  config.url ||= 'api.geonames.org'

  super
end

Instance Method Details

#get_timezone_id(data) (private)

[ GitHub ]

  
# File 'lib/timezone/lookup/geonames.rb', line 50

def get_timezone_id(data)
  return data['timezoneId'] if data['timezoneId']

  return unless config.offset_etc_zones
  return unless data['gmtOffset']
  return unless data['gmtOffset'].is_a? Numeric

  return 'Etc/UTC' if data['gmtOffset'].zero?

  "Etc/GMT#{format('%+d', -data['gmtOffset'])}"
end

#lookup(lat, long)

[ GitHub ]

  
# File 'lib/timezone/lookup/geonames.rb', line 29

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

  return unless response.body

  data = JSON.parse(response.body)

  timezone_id = get_timezone_id(data)
  return timezone_id if timezone_id

  return unless data['status']

  return if NO_TIMEZONE_INFORMATION == data['status']['value']

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

#url(lat, long) (private)

[ GitHub ]

  
# File 'lib/timezone/lookup/geonames.rb', line 62

def url(lat, long)
  query = URI.encode_www_form(
    'lat' => lat,
    'lng' => long,
    'username' => config.username
  )
  "/timezoneJSON?#{query}"
end