lib/geocoder/lookups/base.rb in geocoder-1.1.4 vs lib/geocoder/lookups/base.rb in geocoder-1.1.5

- old
+ new

@@ -89,10 +89,20 @@ def query_url(query) fail end ## + # Key to use for caching a geocoding result. Usually this will be the + # request URL, but in cases where OAuth is used and the nonce, + # timestamp, etc varies from one request to another, we need to use + # something else (like the URL before OAuth encoding). + # + def cache_key(query) + query_url(query) + end + + ## # Class of the result objects # def result_class Geocoder::Result.const_get(self.class.to_s.split(":").last) end @@ -142,28 +152,37 @@ def protocol "http" + (Geocoder::Configuration.use_https ? "s" : "") end ## - # Fetches a raw search result (JSON string). + # Fetch a raw geocoding result (JSON string). + # The result might or might not be cached. # def fetch_raw_data(query) - timeout(Geocoder::Configuration.timeout) do - url = query_url(query) - uri = URI.parse(url) - if cache and body = cache[url] - @cache_hit = true - else - client = http_client.new(uri.host, uri.port) - client.use_ssl = true if Geocoder::Configuration.use_https - response = client.get(uri.request_uri, Geocoder::Configuration.http_headers) - body = response.body - if cache and (200..399).include?(response.code.to_i) - cache[url] = body - end - @cache_hit = false + key = cache_key(query) + if cache and body = cache[key] + @cache_hit = true + else + response = make_api_request(query) + body = response.body + if cache and (200..399).include?(response.code.to_i) + cache[key] = body end - body + @cache_hit = false + end + body + end + + ## + # Make an HTTP(S) request to a geocoding API and + # return the response object. + # + def make_api_request(query) + timeout(Geocoder::Configuration.timeout) do + uri = URI.parse(query_url(query)) + client = http_client.new(uri.host, uri.port) + client.use_ssl = true if Geocoder::Configuration.use_https + client.get(uri.request_uri, Geocoder::Configuration.http_headers) end end ## # The working Cache object.