Rails.cache.clear certain key names?

Shpigford picture Shpigford · Aug 17, 2012 · Viewed 49k times · Source

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.

Answer

Sandip Ransing picture Sandip Ransing · Aug 17, 2012

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