0

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.

steven_noble
  • 4,133
  • 10
  • 44
  • 77
  • While you could probably set up some `before_save` filters to expire the old cache before updating the timestamp, you probably don't need to. See #4 at http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works. The idea is that Memcached will automatically get rid of the unused cache entries once it's "full". – Dylan Markow Aug 07 '13 at 02:10
  • Those design principles probably make sense. In my case, I have a gazillion computed properties, and I'm trying to find a way to flag some of them as needing recalculation/recaching without touching the entire object. – steven_noble Aug 07 '13 at 06:06

0 Answers0