Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache an arbitrary object in Rails(time-based)?

I read the official guide. It says there are page cache, action cache and fragment cache, but they are not what I want.

I just like to cache an object, not the whole page or fragment of view, like this pseudocode:

def show
  cache @ads, :expires_in => 1.hour do
    @ads = Advertisement.all
  do
end

Is it possible? with memcache or redis?

like image 361
Lai Yu-Hsuan Avatar asked Nov 23 '11 02:11

Lai Yu-Hsuan


People also ask

How can you implement caching in Rails?

In order to use page and action caching you will need to add actionpack-page_caching and actionpack-action_caching to your Gemfile . By default, caching is only enabled in your production environment. You can play around with caching locally by running rails dev:cache , or by setting config. action_controller.

What is sweeper in Ruby on Rails?

Sweepers are the terminators of the caching world and responsible for expiring caches when model objects change. They do this by being half-observers, half-filters and implementing callbacks for both roles.

What does Rails cache clear do?

clear will clear your app cache. In that case rake tmp:cache:clear will just try to remove files from "#{Rails. root}/tmp/cache" but probably won't actually do anything since nothing is probably being cached on the filesystem.

Is Rails cache thread safe?

The default Rails cache (ActiveSupport::Cache MemoryStore) is thread-safe as of Rails version 3.1: http://api.rubyonrails.org/v3.1.0/files/activesupport/CHANGELOG.html As the CHANGELOG notes: "Make thread safe so that the default cache implementation used by Rails is thread safe."


2 Answers

Try this:

#To cache the object
Rails.cache.write('cache-key', object)

#Load the object from the cache
Rails.cache.read('cache-key')
like image 159
leonardoborges Avatar answered Nov 09 '22 22:11

leonardoborges


Check out the lawnchair gem to cache objects in Redis.

like image 33
Michelle Tilley Avatar answered Nov 09 '22 21:11

Michelle Tilley