How can I list the keys in the in-memory cache store on Ruby on Rails?
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.
In Rails 6, with Redis used as a cache store
Rails.cache.redis.keys
If you don't need to access the keys dynamically, an easier approach is locating the directory where the cache is stored. A file is created for each entry.
In my case this was at "APP_ROOT/tmp/cache", but you can easily locate it by going to rails console and typing
1.8.7 :030 > Rails.cache.clear
=> ["path_to_rails_app/tmp/cache/6D5"]
Rails.cache.instance_variable_get(:@data).keys