4

I need to get expire or creation time for cache entry.

This is for: sitemap index, each sitemap in index is cached action. I want to add <lastmod> attribute, which, in my case, will be cache entry creation time.

For example for action caching:

class ProductsController < ActionController
  caches_action :index

  def index
    @products = Product.all
  end
end

I need something like this:

Rails.cache.get(:controller=>'products',:action=>'index').created_at
rogal111
  • 5,874
  • 2
  • 27
  • 33

2 Answers2

6

I found solution, which work with all popular cache stores (tested with redis_store, mem_cache_store, memory_store, file_store).

Time.at(Rails.cache.send(:read_entry,'cache/entry/key',{})).created_at)

read_entry method returns ActiveSupport::Cache::Entry object (class documentation)

rogal111
  • 5,874
  • 2
  • 27
  • 33
  • I wonder why Rails doesn't expose the entry itself. Super useful. Thanks for posting your solution. – devth May 03 '13 at 18:42
  • Symbol Error `Time.at(Rails.cache.send(:read_entry,'cache/entry/key',{}).created_at)` not `Time.at(Rails.cache.send(:read_entry,'cache/entry/key',{})).created_at)` – luotao Apr 20 '17 at 04:46
2

For posterity, in Rails 4.2+, you have access in a similar way to @rogal111's answer by way of...

Time.at(Rails.cache.send(:read_entry, key, {}).expires_at)
# And
Rails.cache.send(:read_entry, key, {}).expired?

But unless you want to reach through into the object, you can't access created_at.

To do so you'd need to do something to the effect of

Rails.cache.send(:read_entry, key, {}).instance_variable_get('@created_at')
Volte
  • 1,905
  • 18
  • 25