Sha256: b5bd4ad93541d93724d9be65109c8eb83c7538096d82a6d55c230fa43daf21bf

Contents?: true

Size: 970 Bytes

Versions: 8

Compression:

Stored size: 970 Bytes

Contents

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

module Timezone
  module Lookup
    class Geonames < ::Timezone::Lookup::Basic
      def initialize(config)
        if config.username.nil?
          raise(::Timezone::Error::InvalidConfig, 'missing username')
        end

        super
      end

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

        return unless response.code =~ /^2\d\d$/

        data = JSON.parse(response.body)

        if data['status'] && data['status']['value'] == 18
          raise(Timezone::Error::GeoNames, 'api limit reached')
        end

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

      private

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

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
timezone-0.6.0 lib/timezone/lookup/geonames.rb
timezone-0.5.0 lib/timezone/lookup/geonames.rb
timezone-0.4.3 lib/timezone/lookup/geonames.rb
timezone-0.4.2 lib/timezone/lookup/geonames.rb
timezone-0.4.1 lib/timezone/lookup/geonames.rb
timezone-0.4.0 lib/timezone/lookup/geonames.rb
timezone-0.3.11 lib/timezone/lookup/geonames.rb
timezone-0.3.10 lib/timezone/lookup/geonames.rb