diff --git a/examples/autoexpire_cache_dalli.rb b/examples/autoexpire_cache_dalli.rb new file mode 100644 index 0000000000000000000000000000000000000000..16fc77c2f5d736af39ff52711cee5257c559a715 --- /dev/null +++ b/examples/autoexpire_cache_dalli.rb @@ -0,0 +1,62 @@ +# This class implements a cache with simple delegation to the the Dalli Memcached client +# https://github.com/mperham/dalli +# +# A TTL is set on initialization + +class AutoexpireCacheDalli + def initialize(store, ttl = 86400) + @store = store + @keys = 'GeocoderDalliClientKeys' + @ttl = ttl + end + + def [](url) + res = @store.get(url) + res = YAML::load(res) if res.present? + res + end + + def []=(url, value) + if value.nil? + del(url) + else + key_cache_add(url) if @store.add(key, YAML::dump(value), @ttl) + end + value + end + + def keys + key_cache + end + + def del(url) + key_cache_delete(url) if @store.delete(key) + end + + private + + def key_cache + the_keys = @store.get(@keys) + if the_keys.nil? + @store.add(@keys, YAML::dump([])) + [] + else + YAML::load(the_keys) + end + end + + def key_cache_add(key) + @store.replace(@keys, YAML::dump(key_cache << key)) + end + + def key_cache_delete(key) + tmp = key_cache + tmp.delete(key) + @store.replace(@keys, YAML::dump(tmp)) + end +end + +# Here Dalli is set up as on Heroku using the Memcachier gem. +# https://devcenter.heroku.com/articles/memcachier#ruby +# On other setups you might have to specify your Memcached server in Dalli::Client.new +Geocoder.configure(:cache => AutoexpireCacheDalli.new(Dalli::Client.new)) diff --git a/examples/autoexpire_cache.rb b/examples/autoexpire_cache_redis.rb similarity index 76% rename from examples/autoexpire_cache.rb rename to examples/autoexpire_cache_redis.rb index ced862b3d875a81bf701d4dc5356e3587382371a..1b67a9eee0febd18c6ba6c11cb35a3acfce18f2b 100644 --- a/examples/autoexpire_cache.rb +++ b/examples/autoexpire_cache_redis.rb @@ -1,10 +1,10 @@ # This class implements a cache with simple delegation to the Redis store, but # when it creates a key/value pair, it also sends an EXPIRE command with a TTL. # It should be fairly simple to do the same thing with Memcached. -class AutoexpireCache - def initialize(store) +class AutoexpireCacheRedis + def initialize(store, ttl = 86400) @store = store - @ttl = 86400 + @ttl = ttl end def [](url) @@ -25,4 +25,4 @@ class AutoexpireCache end end -Geocoder.configure(:cache => AutoexpireCache.new(Redis.new)) +Geocoder.configure(:cache => AutoexpireCacheRedis.new(Redis.new)) \ No newline at end of file