Rails.cache.clear certain key names?

Ruby on-RailsCachingMemcachedDalli

Ruby on-Rails Problem Overview


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.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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' }

Solution 2 - Ruby on-Rails

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).

Solution 3 - Ruby on-Rails

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShpigfordView Question on Stackoverflow
Solution 1 - Ruby on-RailsSandip RansingView Answer on Stackoverflow
Solution 2 - Ruby on-RailsShpigfordView Answer on Stackoverflow
Solution 3 - Ruby on-RailsfkoesslerView Answer on Stackoverflow