Ruby on rails Rails缓存:替换Rails.cache.fetch中的expires\u

Ruby on rails Rails缓存:替换Rails.cache.fetch中的expires\u,ruby-on-rails,Ruby On Rails,在保持“get或set”缓存调用的简洁性的同时,清除此警告的最佳方法是什么?我真的很喜欢不必做一个get,然后检查零,然后设置 # DEPRECATION WARNING: Setting :expires_in on read has been deprecated in favor of setting it on write. @foo = Rails.cache.fetch("some_key", :expires_in => 15.minutes) do some st

在保持“get或set”缓存调用的简洁性的同时,清除此警告的最佳方法是什么?我真的很喜欢不必做一个get,然后检查零,然后设置

# DEPRECATION WARNING: Setting :expires_in on read has been deprecated in favor of setting it on write.

@foo = Rails.cache.fetch("some_key", :expires_in => 15.minutes) do
    some stuff
end
使用 及 从我所能找到的来看,这似乎是你唯一的选择

我真的很喜欢不必做一个get,然后检查零,然后设置

# DEPRECATION WARNING: Setting :expires_in on read has been deprecated in favor of setting it on write.

@foo = Rails.cache.fetch("some_key", :expires_in => 15.minutes) do
    some stuff
end
是的,您希望避免在每次通话中都这样做,但您仍然必须至少这样做一次。像这样简单的事情可能适合你:

def smart_fetch(name, options, &blk)
  in_cache = Rails.cache.fetch(name)
  return in_cache if in_cache
  val = yield
  Rails.cache.write(name, val, options)
  return val
end
然后在您的视图中,您可以执行以下操作:

@foo = smart_fetch("some_key") do
  some stuff
end

请注意,Rails缓存存储有一个默认的到期时间,您可以在创建它时设置它,因此您可能不需要在每次调用时覆盖它,除非您需要不同的到期时间。

对@briandoll提供的有用方法进行了一些小改动:

def smart_fetch(name, options = {}, &blk)
  in_cache = Rails.cache.fetch(name)
  return in_cache if in_cache
  if block_given? 
    val = yield 
    Rails.cache.write(name, val, options) 
    return val 
  end 
end

顺便说一句,rails 3.1通过在默认堆栈中添加rack::cache对其进行了一些修改:fresh_when和expires_when是与HTTP响应相关的控制器方法;问题是关于不考虑web服务的通用数据缓存。只想注意,在Rails 4中,有更多的趋势是使用无需过期时间的俄罗斯玩偶缓存。过期时间仍然可以更容易,但现在这有时是一种反模式。Rails 4没有针对该语法给出弃用警告。