How to get fragment expiration date in Rails 3.1?

别说谁变了你拦得住时间么 提交于 2020-01-01 16:41:46

问题


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

回答1:


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)




回答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')


来源:https://stackoverflow.com/questions/8243846/how-to-get-fragment-expiration-date-in-rails-3-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!