jmccartie
jmccartie

Reputation: 4976

Rails caching: replacement for expires_in on Rails.cache.fetch

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

Answers (3)

Karmen Blake
Karmen Blake

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

briandoll
briandoll

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

Related Questions