Created
April 18, 2013 10:22
-
-
Save weibel/5411705 to your computer and use it in GitHub Desktop.
Memcached/Dalli cache client for the Ruby Geocoder gem http://www.rubygeocoder.com/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'dalli/client' | |
require 'yaml' | |
class GeocoderDalliClient | |
def initialize | |
@keys = 'GeocoderDalliClientKeys' | |
# setup for Heroku using the memcachier gem. | |
# On other setups you'll have to specify the Memcached server | |
@dalli_client = Dalli::Client.new | |
end | |
def [](key) | |
res = @dalli_client.get(key) | |
res = YAML::load(res) if res.present? | |
res | |
end | |
def []=(key, value) | |
if value.nil? | |
del(key) | |
else | |
key_cache_add(key) if @dalli_client.add(key, YAML::dump(value)) | |
end | |
value | |
end | |
def keys | |
key_cache | |
end | |
def del(key) | |
key_cache_delete(key) if @dalli_client.delete(key) | |
end | |
private | |
def key_cache | |
the_keys = @dalli_client.get(@keys) | |
if the_keys.nil? | |
@dalli_client.add(@keys, YAML::dump([])) | |
[] | |
else | |
YAML::load(the_keys) | |
end | |
end | |
def key_cache_add(key) | |
@dalli_client.replace(@keys, YAML::dump(key_cache << key)) | |
end | |
def key_cache_delete(key) | |
tmp = key_cache | |
tmp.delete(key) | |
@dalli_client.replace(@keys, YAML::dump(tmp)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment