lib/geonames_api/base.rb in geonames_api-0.1.4 vs lib/geonames_api/base.rb in geonames_api-0.1.5

- old
+ new

@@ -1,6 +1,6 @@ -require 'cgi' +require 'uri' module GeoNamesAPI class Base < Entity def self.find(*names_or_params) @@ -17,13 +17,13 @@ end end def self.where(params={}) retries_remaining = GeoNamesAPI.retries - url = url(params) + uri = uri(params) begin - response = make_request(url) + response = make_request(uri) unless response.empty? parse_response(response, params) end rescue Timeout => e if retries_remaining > 0 @@ -36,35 +36,35 @@ raise e end end end - def self.make_request(url) - JSON.load(open(url).read) + def self.make_request(uri) + JSON.load(open(uri, "User-Agent" => "#{GeoNamesAPI.name}/#{GeoNamesAPI::VERSION}").read) end private_class_method :make_request - KEYS = %w(streetSegment geonames) - def self.parse_response(response, request_params) GeoNamesAPI.logger.info "GEONAMES RESPONSE (#{Time.now}): #{response}" if GeoNamesAPI.logger if (status = response['status']) raise Error.from_status(status) end new(response, request_params) end private_class_method :parse_response - def self.url(params={}) - endpoint = GeoNamesAPI.url + self::METHOD + params_to_url(GeoNamesAPI.params.merge(params)) + def self.uri(params={}) + endpoint = URI(GeoNamesAPI.url) + endpoint.path = "/%s" % self::METHOD # URI.path requires a leading / + endpoint.query = URI.encode_www_form(GeoNamesAPI.params.merge(params)) GeoNamesAPI.logger.info "GEONAMES REQUEST (#{Time.now}): #{endpoint}" if GeoNamesAPI.logger endpoint end - private_class_method :url + private_class_method :uri def self.name_params(names) return names.first if names.first.is_a? Hash params, n = {}, 0 if names.any? @@ -73,21 +73,7 @@ params.delete_if { |k, v| v.blank? } end private_class_method :name_params - def self.params_to_url(params={}) - esc_params = params.map do |key, value| - "#{esc(key)}=#{esc(value)}" - end - "?#{esc_params.join('&')}" - end - - private_class_method :params_to_url - - def self.esc(str) - CGI::escape(str.to_s) - end - - private_class_method :esc end end