Skip to content
Snippets Groups Projects
Commit 12fd7811 authored by Alex Reisner's avatar Alex Reisner
Browse files

Add support for result caching.

Just set Geocoder::Configuration.cache to any key/value store that
implements #[], #[]=, and #keys. You can also set
Geocoder::Configuration.cache_prefix to use a custom prefix for keys.
parent 16deb475
No related branches found
No related tags found
No related merge requests found
...@@ -16,10 +16,20 @@ module Geocoder ...@@ -16,10 +16,20 @@ module Geocoder
# app id (if using Yahoo geocoding service) # app id (if using Yahoo geocoding service)
def self.yahoo_appid; @@yahoo_appid; end def self.yahoo_appid; @@yahoo_appid; end
def self.yahoo_appid=(obj); @@yahoo_appid = obj; end def self.yahoo_appid=(obj); @@yahoo_appid = obj; end
# cache object (must respond to #[], #[]=, and #keys
def self.cache; @@cache; end
def self.cache=(obj); @@cache = obj; end
# cache object (must respond to #[], #[]=, and #keys
def self.cache_prefix; @@cache_prefix; end
def self.cache_prefix=(obj); @@cache_prefix = obj; end
end end
end end
Geocoder::Configuration.timeout = 3 Geocoder::Configuration.timeout = 3
Geocoder::Configuration.lookup = :google Geocoder::Configuration.lookup = :google
Geocoder::Configuration.language = :en Geocoder::Configuration.language = :en
Geocoder::Configuration.yahoo_appid = "" Geocoder::Configuration.yahoo_appid = ""
Geocoder::Configuration.cache = nil
Geocoder::Configuration.cache_prefix = "geocoder:"
...@@ -83,11 +83,39 @@ module Geocoder ...@@ -83,11 +83,39 @@ module Geocoder
# #
def fetch_raw_data(query, reverse = false) def fetch_raw_data(query, reverse = false)
url = query_url(query, reverse) url = query_url(query, reverse)
key = cache_key(url)
timeout(Geocoder::Configuration.timeout) do timeout(Geocoder::Configuration.timeout) do
Net::HTTP.get_response(URI.parse(url)).body unless cache and (response = cache[key]) and response != ""
response = Net::HTTP.get_response(URI.parse(url)).body
if cache
cache[key] = response
end
end
response
end end
end end
##
# Cache key for a given URL.
#
def cache_key(url)
[cache_prefix, url].join
end
##
# The configured prefix for cache keys.
#
def cache_prefix
Geocoder::Configuration.cache_prefix || "geocoder:"
end
##
# The configured cache store.
#
def cache
Geocoder::Configuration.cache
end
## ##
# Is the given string a loopback IP address? # Is the given string a loopback IP address?
# #
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment