【问题标题】:How to get fragment expiration date in Rails 3.1?如何在 Rails 3.1 中获取片段到期日期?
【发布时间】:2012-01-04 20:13:42
【问题描述】:

我需要获取缓存条目的过期时间或创建时间。

这是针对:sitemap index,索引中的每个站点地图都是缓存操作。我想添加 <lastmod> 属性,在我的例子中是缓存条目的创建时间。

例如对于动作缓存:

class ProductsController < ActionController
  caches_action :index

  def index
    @products = Product.all
  end
end

我需要这样的东西:

Rails.cache.get(:controller=>'products',:action=>'index').created_at

【问题讨论】:

  • 您是否要扫描缓存?众所周知,Rails 内置了缓存扫描功能。
  • @DevinM 用于站点地图索引,我编辑了问题。

标签: ruby-on-rails ruby-on-rails-3 caching


【解决方案1】:

我找到了适用于所有流行缓存存储的解决方案(使用 redis_store、mem_cache_store、memory_store、file_store 测试)。

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

read_entry 方法返回ActiveSupport::Cache::Entry 对象(class documentation

【讨论】:

  • 我想知道为什么 Rails 不公开条目本身。超级好用。感谢您发布您的解决方案。
  • 符号错误 Time.at(Rails.cache.send(:read_entry,'cache/entry/key',{}).created_at) 不是 Time.at(Rails.cache.send(:read_entry,'cache/entry/key',{})).created_at)
【解决方案2】:

对于后代,在 Rails 4.2+ 中,您可以通过类似的方式访问@rogal111 的答案...

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

但除非你想进入对象,否则你无法访问created_at

要做到这一点,你需要做一些事情来实现

Rails.cache.send(:read_entry, key, {}).instance_variable_get('@created_at')

【讨论】:

  • 感谢您拯救了我的一天!非常感谢您的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 2013-12-28
  • 2013-12-01
  • 1970-01-01
  • 2012-12-05
相关资源
最近更新 更多