I am using Rails 3.
How can I list the keys in the in-memory cache store on Ruby on Rails?
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 .
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.
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.
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.
Rails.cache.instance_variable_get(:@data).keys
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With