How can I automatically delete these redundant cache entries?

433 Views Asked by At

Let's say I create a new object in my Category class:

> @category = Category.create :name => "foo"
+----+------+-------------------------+-------------------------+
| id | name | created_at              | updated_at              |
+----+------+-------------------------+-------------------------+
| 13 | foo  | 2013-08-06 22:38:51 UTC | 2013-08-06 22:38:51 UTC |
+----+------+-------------------------+-------------------------+
1 row in set

I can store the value of @category.name in Rails.cache if it's not stored there already:

> Rails.cache.fetch([@category, "name"]) {@category.name}
Cache read: categories/13-20130806223851/name
Cache generate: categories/13-20130806223851/name
Cache write: categories/13-20130806223851/name
=> "foo"

That record has a unique cache-key of categories/13-20130806223851/name.

I can read that value back using the key.

> Rails.cache.read([@category, "name"])
Cache read: categories/13-20130806223851/name
=> "foo"

If I @category.touch, its cache_key changes, and the look-up no longer retrieves the stored value.

> @category.touch
=> true

> Rails.cache.read([@category, "name"])
Cache read: categories/13-20130806224755/name
=> nil

That's just what we want. But the old key-value pair is still in the cache:

> Rails.cache.read("categories/13-20130806223851/name")
Cache read: categories/13-2013080

Short of flushing my entire cache, how can I ensure the old key-value pair is automatically deleted? Ideally I'm looking for a solution that will instantly apply to everything I store in the cache.

BTW I'm on Rails 3.2 and Ruby 1.9.3.

0

There are 0 best solutions below