Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 860
jmccartie Avatar asked May 27 '11 19:05

jmccartie


People also ask

What is Rails cache fetch?

The most efficient way to implement low-level caching is using the Rails. cache. fetch method. This method does both reading and writing to the cache. When passed only a single argument, the key is fetched and value from the cache is returned.

What is low level cache?

What is Low-Level Caching. What Rails calls low level caching is really just reading and writing data to a key-value store. Out of the box, Rails supports an in-memory store, files on the filesystem, and external stores like Redis or memcached. It is called "low level" caching because you are dealing with the Rails.

How does Rails query cache work?

Rails provides an SQL query cache which is used to cache the results of database queries for the duration of a request. When Rails encounters the same query again within the same request, it uses the cached result set instead of running the query against the database again.

Where is Rails cache stored?

By default, the page cache directory is set to Rails. public_path (which is usually set to the public folder) and this can be configured by changing the configuration setting config. action_controller.


1 Answers

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.

like image 55
briandoll Avatar answered Oct 13 '22 00:10

briandoll