Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I list the keys in the in-memory cache store on Ruby on Rails?

I am using Rails 3.

How can I list the keys in the in-memory cache store on Ruby on Rails?

like image 734
Nerian Avatar asked Mar 07 '12 13:03

Nerian


People also ask

How do I access Rails cache?

You can play around with caching locally by running rails dev:cache , or by setting config. action_controller. perform_caching to true in config/environments/development. rb .

Does Rails cache use Redis?

To use Redis as a Rails cache store, use a dedicated Redis cache that's set up as a LRU (Last Recently Used) cache instead of pointing the store at your existing Redis server, to make sure entries are dropped from the store when it reaches its maximum size.

What is cache sweeper in Rails?

Cache sweeping is a mechanism which allows you to get around having a ton of expire_{page,action,fragment} calls in your code. It does this by moving all the work required to expire cached content into na ActionController::Caching::Sweeper class.

What is Russian doll caching?

Ruby on Rails Caching Russian Doll Caching You may want to nest cached fragments inside other cached fragments. This is called Russian doll caching . The advantage of Russian doll caching is that if a single product is updated, all the other inner fragments can be reused when regenerating the outer fragment.


2 Answers

Rails.cache.instance_variable_get(:@data).keys 
like image 113
Michał Dulat Avatar answered Sep 17 '22 14:09

Michał Dulat


ActiveSupport::Cache::MemoryStore doesn't provide a way to access the store's keys directly (and neither does its parent class ActiveSupport::Cache::Store).

Internally MemoryStore keeps everything in a Hash called @data, however, so you could monkey-patch or subclass it to get the keys, e.g.:

class InspectableMemoryStore < ActiveSupport::Cache::MemoryStore   def keys     @data.keys   end end  ActionController::Base.cache_store = InspectableMemoryStore.new  Rails.cache.keys # => [ "foo", ... ] 

This comes with the usual caveat, however: MemoryStore's internal implementation may change at any time and @data may disappear or be changed to something that doesn't respond_to? :keys. A smarter implementation might be to override the write and delete methods (since, as part of the public API, they're unlikely to change unexpectedly) to keep your own list of keys, e.g.:

class InspectableMemoryStore < ActiveSupport::Cache::MemoryStore   def write *args     super      @inspectable_keys[ args[0] ] = true   end    def delete *args     super      @inspectable_keys.delete args[0]   end    def keys     @inspectable_keys.keys   end end 

This is a very naive implementation, and of course keeping the keys in an additional structure takes up some memory, but you get the gist.

like image 41
Jordan Running Avatar answered Sep 17 '22 14:09

Jordan Running