lib/geocoder/lookups/base.rb in geocoder-1.1.8 vs lib/geocoder/lookups/base.rb in geocoder-1.1.9

- old
+ new

@@ -70,11 +70,11 @@ # URL to use for querying the geocoding engine. # def query_url(query) fail end - + ## # The working Cache object. # def cache if @cache.nil? and store = configuration.cache @@ -97,11 +97,11 @@ # def http_client protocol = "http#{'s' if configuration.use_https}" proxy_name = "#{protocol}_proxy" if proxy = configuration.send(proxy_name) - proxy_url = protocol + '://' + proxy + proxy_url = !!(proxy =~ /^#{protocol}/) ? proxy : protocol + '://' + proxy begin uri = URI.parse(proxy_url) rescue URI::InvalidURIError raise ConfigurationError, "Error parsing #{protocol.upcase} proxy URL: '#{proxy_url}'" @@ -169,19 +169,23 @@ rescue TimeoutError => err raise_error(err) or warn "Geocoding API not responding fast enough " + "(use Geocoder.configure(:timeout => ...) to set limit)." end + def parse_json(data) + if defined?(ActiveSupport::JSON) + ActiveSupport::JSON.decode(data) + else + JSON.parse(data) + end + end + ## # Parses a raw search result (returns hash or array). # def parse_raw_data(raw_data) - if defined?(ActiveSupport::JSON) - ActiveSupport::JSON.decode(raw_data) - else - JSON.parse(raw_data) - end + parse_json(raw_data) rescue warn "Geocoding API's response was not valid JSON." end ## @@ -190,10 +194,14 @@ # def protocol "http" + (configuration.use_https ? "s" : "") end + def valid_response?(response) + (200..399).include?(response.code.to_i) + end + ## # Fetch a raw geocoding result (JSON string). # The result might or might not be cached. # def fetch_raw_data(query) @@ -202,11 +210,11 @@ @cache_hit = true else check_api_key_configuration!(query) response = make_api_request(query) body = response.body - if cache and (200..399).include?(response.code.to_i) + if cache and valid_response?(response) cache[key] = body end @cache_hit = false end body @@ -217,12 +225,19 @@ # return the response object. # def make_api_request(query) timeout(configuration.timeout) do uri = URI.parse(query_url(query)) - client = http_client.new(uri.host, uri.port) - client.use_ssl = true if configuration.use_https - client.get(uri.request_uri, configuration.http_headers) + # client = http_client.new(uri.host, uri.port) + # client.use_ssl = true if configuration.use_https + # client.get(uri.request_uri, configuration.http_headers) + + http_client.start(uri.host, uri.port) do |client| + client.use_ssl = true if configuration.use_https + req = Net::HTTP::Get.new(uri.request_uri, configuration.http_headers) + req.basic_auth(uri.user, uri.password) if uri.user and uri.password + client.request(req) + end end end def check_api_key_configuration!(query) key_parts = query.lookup.required_api_key_parts