Rails.cache.clear certain key names?
Asked Answered
C

4

81

Is it possible to somehow run Rails.cache.clear and only clear keys with a certain name/string?

I don't want to clear the entire cache...just keys with the string blog/post in the name (ie. blog/post/1, blog/post/2).

I'm using dalli with memcached for my cache and running Rails 3.0.6.

Colecolectomy answered 17/8, 2012 at 12:2 Comment(0)
C
14

To answer my own question...it seems that given I'm using memcached, I actually can't use delete_if or delete_matched because memcached does not support enumerating or querying keys by pattern (1).

Colecolectomy answered 17/8, 2012 at 15:16 Comment(1)
So, What is the solution while using memcache ?Vachill
C
133

This is how you can write to cache -

Rails.cache.write('key', 'value', :time_to_idle => 60.seconds, :timeToLive => 600.seconds)

and in order to delete from cache you can use delete action -

Rails.cache.delete('key')

Delete multiple keys -

Rails.cache.delete_if {|k, v| k =~ 'key' }
Cardboard answered 17/8, 2012 at 12:23 Comment(5)
Right, but I need to delete all keys that contain a certain string in their name. For instance, all keys that have blog/post in the name of the key.Colecolectomy
@Colecolectomy Rails.cache is just a hash ..look for the hash documentation in order to delete multiple keys :)Cardboard
I'm geting an 'undefined method' error for delete_if. I'm running Rails 3.0.6.Colecolectomy
Also, forgot to mention, I'm using Dalli w/ memcached as my cache.Colecolectomy
time to idle and time to live seems for EH cache only guides.rubyonrails.org/…Taliataliaferro
C
14

To answer my own question...it seems that given I'm using memcached, I actually can't use delete_if or delete_matched because memcached does not support enumerating or querying keys by pattern (1).

Colecolectomy answered 17/8, 2012 at 15:16 Comment(1)
So, What is the solution while using memcache ?Vachill
W
3

You can use the https://github.com/Phobos98/dalli-delete-matched gem that adds a simple implementation of delete_matched method for dalli store with memcached.

Wineglass answered 14/4, 2016 at 8:17 Comment(1)
Does that work in a multi-server environment? The gem looks like it stores the keys on the cache server without any guards to prevent multiple writersAntagonistic
C
0

I add some dependency in the cache key, for example Rails.cache.fetch("blog_#{blog.posts.order(:id).last.updated_at}_stat"). So this key will expire automatically when any post changed.

Chenay answered 10/6, 2023 at 6:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.