Sha256: 0c138fc29fb9328fdd081cd57cea6f88f8f6cbfd576ac6259f44ebf9ef70a336

Contents?: true

Size: 1.17 KB

Versions: 10

Compression:

Stored size: 1.17 KB

Contents

module Qa::Authorities
  class Geonames < Base
    include WebServiceBase

    class_attribute :username, :label

    self.label = lambda do |item|
      [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

    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|
          # Note: the trailing slash is meaningful.
          { 'id' => "http://sws.geonames.org/#{result['geonameId']}/",
            'label' => label.call(result) }
        end
      end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
qa-3.1.0 lib/qa/authorities/geonames.rb
qa-2.3.0 lib/qa/authorities/geonames.rb
qa-3.0.0 lib/qa/authorities/geonames.rb
qa-2.2.0 lib/qa/authorities/geonames.rb
qa-2.1.2 lib/qa/authorities/geonames.rb
qa-2.1.1 lib/qa/authorities/geonames.rb
qa-2.0.1 lib/qa/authorities/geonames.rb
qa-2.0.0 lib/qa/authorities/geonames.rb
qa-1.2.0 lib/qa/authorities/geonames.rb
qa-1.1.0 lib/qa/authorities/geonames.rb