From 12fd7811aabbbe4c6a9595715a5ed0c6791c7f80 Mon Sep 17 00:00:00 2001 From: Alex Reisner <alex@alexreisner.com> Date: Tue, 15 Mar 2011 19:19:48 -0400 Subject: [PATCH] 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. --- lib/geocoder/configuration.rb | 18 ++++++++++++++---- lib/geocoder/lookups/base.rb | 30 +++++++++++++++++++++++++++++- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/lib/geocoder/configuration.rb b/lib/geocoder/configuration.rb index 79588190..a76572a1 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 220c3f58..65ff2128 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? # -- GitLab