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

3

6

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?

Baillargeon answered 23/11, 2011 at 2:26 Comment(1)
Caching objects means serialization (usually through Marshal.dump/Marshal.load). Be careful as some objects cannot be serialized. Some others have large object graphs (attributes and variables that point to other, large, objects) which can be both expensive to serialize/unserialize and can take up a lot more space than you expect. For example, "caching" ActiveRecord objects by serializing them to redis/memcache is not a good idea.Bathsheb
S
3

Try this:

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

#Load the object from the cache
Rails.cache.read('cache-key')
Simonsen answered 23/11, 2011 at 3:48 Comment(0)
N
1

Check out the lawnchair gem to cache objects in Redis.

Nicker answered 23/11, 2011 at 2:33 Comment(0)
T
0
Rails.cache.write(cache_key, your_value, expires_in: 10.seconds)

Rails.cache.readh(cache_key)
Thorton answered 10/2, 2020 at 11:29 Comment(1)
Could you maybe elaborate on your code a bit more, maybe by explaining it?Melainemelamed

© 2022 - 2024 — McMap. All rights reserved.