Sha256: d1a630a0d3abbcfe3d5767897f19cc9adcb685ce6fb16967e74c26cadad8d3a5

Contents?: true

Size: 1.2 KB

Versions: 4

Compression:

Stored size: 1.2 KB

Contents

module Qa::Authorities
  class Geonames < Base
    include WebServiceBase

    class_attribute :username, :label

    self.label = -> (item) do
      [item['name'], item['adminName1'], item['countryName']].compact.join(', ')
    end

    def search q
      unless username
        Rails.logger.error "Questioning Authority tried to call geonames, but no username was set"
        return []
      end
      parse_authority_response(json(build_query_url(q)))
    end

    # get_json is not ideomatic, so we'll make an alias
    def json(*args)
      get_json(*args)
    end

    def build_query_url q
      query = URI.escape(untaint(q))
      "http://api.geonames.org/searchJSON?q=#{query}&username=#{username}&maxRows=10"
    end

    def untaint(q)
      q.gsub(/[^\w\s-]/, '')
    end

    def find id
      json(find_url(id))
    end

    def find_url id
      "http://www.geonames.org/getJSON?geonameId=#{id}&username=#{username}"
    end

    private

    # Reformats the data received from the service
    def parse_authority_response(response)
      response['geonames'].map do |result|
        { 'id' => "http://sws.geonames.org/#{result['geonameId']}",
          'label' => label.call(result) }
      end
    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
qa-0.10.1 lib/qa/authorities/geonames.rb
qa-0.10.0 lib/qa/authorities/geonames.rb
qa-0.9.0 lib/qa/authorities/geonames.rb
qa-0.8.0 lib/qa/authorities/geonames.rb