Rails.cache
, provided by ActiveSupport, can be used to cache any serializable Ruby object across requests.
To fetch a value from the cache for a given key, use cache.read
:
Rails.cache.read('city')
# => nil
Use cache.write
to write a value to the cache:
Rails.cache.write('city', 'Duckburgh')
Rails.cache.read('city')
# => 'Duckburgh'
Alternatively, use cache.fetch
to read a value from the cache and optionally write a default if there is no value:
Rails.cache.fetch('user') do
User.where(:is_awesome => true)
end
The return value of the passed block will be assigned to the cache under the given key, and then returned.
You can also specify a cache expiry:
Rails.cache.fetch('user', :expires_in => 30.minutes) do
User.where(:is_awesome => true)
end