问题描述
||
在保持简短的“ get or set”缓存调用的同时,清除此警告的最佳方法是什么?我真的很喜欢不必做,然后检查零,然后设置...
# 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,options)
return val
end
end
, 使用
http://apidock.com/rails/ActionController/ConditionalGet/fresh_when
和
http://apidock.com/rails/ActionController/ConditionalGet/expires_in
根据我的发现,这似乎是您唯一的选择。