Sha256: d5d4c692d886929ba4540643dd93e6a25396a2e2e8383c61416da0f46ce5c1a0

Contents?: true

Size: 1.78 KB

Versions: 9

Compression:

Stored size: 1.78 KB

Contents

require 'timezone/lookup/basic'
require 'timezone/error'
require 'json'
require 'uri'

module Timezone
  module Lookup
    # @!visibility private
    class Geonames < ::Timezone::Lookup::Basic
      # 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.
      NO_TIMEZONE_INFORMATION = 15

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

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

        super
      end

      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 => e
        raise(Timezone::Error::GeoNames, e.message)
      end

      private

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

        if config.offset_etc_zones && data['gmtOffset']
          return unless data['gmtOffset'].is_a? Numeric
          return 'Etc/UTC' if data['gmtOffset'] == 0
          "Etc/GMT#{format('%+d', -data['gmtOffset'])}"
        end
      end

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

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
timezone-1.2.8 lib/timezone/lookup/geonames.rb
timezone-1.2.7 lib/timezone/lookup/geonames.rb
timezone-1.2.6 lib/timezone/lookup/geonames.rb
timezone-1.2.5 lib/timezone/lookup/geonames.rb
timezone-1.2.4 lib/timezone/lookup/geonames.rb
timezone-1.2.3 lib/timezone/lookup/geonames.rb
timezone-1.2.2 lib/timezone/lookup/geonames.rb
timezone-1.2.1 lib/timezone/lookup/geonames.rb
timezone-1.2.0 lib/timezone/lookup/geonames.rb