diff --git a/lib/geocoder/configuration.rb b/lib/geocoder/configuration.rb index 795881904d5bf1aafa36f4f9a1a3a49cf92c2c9c..a76572a13afe5ab56e6fa018d6e74dfddbc0ef0d 100644 --- a/lib/geocoder/configuration.rb +++ b/lib/geocoder/configuration.rb @@ -16,10 +16,20 @@ module Geocoder # app id (if using Yahoo geocoding service) def self.yahoo_appid; @@yahoo_appid; 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 -Geocoder::Configuration.timeout = 3 -Geocoder::Configuration.lookup = :google -Geocoder::Configuration.language = :en -Geocoder::Configuration.yahoo_appid = "" +Geocoder::Configuration.timeout = 3 +Geocoder::Configuration.lookup = :google +Geocoder::Configuration.language = :en +Geocoder::Configuration.yahoo_appid = "" +Geocoder::Configuration.cache = nil +Geocoder::Configuration.cache_prefix = "geocoder:" diff --git a/lib/geocoder/lookups/base.rb b/lib/geocoder/lookups/base.rb index 220c3f588fc8fcdf0a7e7a50e0e6abc38e8349dc..65ff21281ef655b5186f5810e4b4a3cc5ff133a0 100644 --- a/lib/geocoder/lookups/base.rb +++ b/lib/geocoder/lookups/base.rb @@ -83,11 +83,39 @@ module Geocoder # def fetch_raw_data(query, reverse = false) url = query_url(query, reverse) + key = cache_key(url) 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 + ## + # 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? #