Skip to content

Instantly share code, notes, and snippets.

@mhorbul
Created March 4, 2010 00:52
Show Gist options
  • Save mhorbul/321267 to your computer and use it in GitHub Desktop.
Save mhorbul/321267 to your computer and use it in GitHub Desktop.
ActiveSupport::Cache::MemCacheStore extension
#
# MemCacheStore extension which allows to find and delete the objects from cache by keys matched regexp.
#
# Idea was taken from http://github.com/martincik/memcache_store_with_delete_matched/
module ActiveSupport
module Cache
class MemCacheStore < Store
cattr_accessor :keys_key_name
def write_with_matched(key, value, options = nil)
flush_keys(key) if write_without_matched(key, value, options)
end
alias_method_chain :write, :matched
def delete_with_matched(key, options = nil)
if delete_without_matched(key, options)
keys.delete(key)
flush_keys
end
end
alias_method_chain :delete, :matched
def delete_matched(matcher, options = nil)
super
keys.dup.each do |key|
if key =~ matcher
keys.delete(key) if delete_without_matched(key, options)
end
end
flush_keys
end
def keys_key_name
@@keys_key_name ||= "mem_cache_store_keys"
end
private
def keys
@keys ||= begin
YAML.load(read(keys_key_name))
rescue TypeError
[]
end
end
def flush_keys(key = nil)
unless key.nil? || keys.include?(key)
keys << key
end
write_without_matched(keys_key_name, keys.compact.to_yaml)
@keys = nil
end
end
end
end
require File.dirname(__FILE__) + '/../spec_helper'
describe ActiveSupport::Cache::MemCacheStore do
let(:cache) { ActiveSupport::Cache.lookup_store(:mem_cache_store) }
context "with #delete_matched" do
it "should find and delete objects by keys matched to regexp" do
cache.write("1_0", "foo_1_0")
cache.write("2_0", "foo_2_0")
cache.write("2_1", "foo_2_1")
cache.delete_matched(/2_.*/)
cache.read("1_0").should == "foo_1_0"
cache.read("2_0").should be_nil
cache.read("2_1").should be_nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment