Reputation: 4976
What's the best way to clear up this warning while keeping the brevity of the "get or set" caching call? I really like not having to do a get, then check for nil, then 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
Upvotes: 7
Views: 7643
Reputation: 3436
Small alterations to the helpful method provided by @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
Upvotes: 5
Reputation: 311
I really like not having to do a get, then check for nil, then set...
Yes, you'll want to avoid doing that on every call, but you'll still have to do that at least once. Something simple like this may work for you:
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
Then in your views you can do:
@foo = smart_fetch("some_key") do
some stuff
end
Note that the Rails cache store has a default expiry time you can set when you create it, so you may not need to override that on each call unless you need different expiry times.
Upvotes: 5
Reputation: 762
Using http://apidock.com/rails/ActionController/ConditionalGet/fresh_when and http://apidock.com/rails/ActionController/ConditionalGet/expires_in seem to be your only option from what I can find.
Upvotes: 0