Cory O'Daniel – These are just words Software development, thoughts, and randomness

10Feb/101

Expiring rails fragement caches using an expires time instead of a sweeper (expires_in) – (a ‘duh’ post)

So, I'm setting up fragment caching for some stuff, and I honestly don't care about setting up an observer to sweep some stuff. I just want to cache this one slow fragment for like 5 minutes. I've seen these tutorials all over the web that shows people using the expires_in setting to auto-expire cache like so:

1
Rails.cache.write('test_key', 'test_value', :expires_in => 5.minutes)

That's great and all, but how the hell do I use it for a Page, Action or Fragment cache? Well you just pass the same :expires_in param and yay it works as long as its a mem_cache_store (although, I did see a hackaroo for file_store)

Even the Rails Guide on caching mentions 'expires_in' but doesn't show how to use it.

1
2
3
class StupidController < ApplicationController
  caches_page :whatever, :expires_in => 5.minutes
end

What really got me was when I was trying to use it with a fragment cache. I tried this and it didn't work:

1
- cache(:action => 'home', :action_suffix => 'advertisements', :expires_in => 10.minutes) do

Why? Well, the cache method takes two hashes, and if you leave off the curly braces, that expires_in ends up in the first one, which is used for the name... To roll it right do:

1
- cache({:action => 'home', :action_suffix => 'advertisements'}, :expires_in => 10.minutes) do

Duh, the more you know.

Post to Twitter Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Comments (1) Trackbacks (0)
  1. Hello Sir,

    We are from India a small Web development company… I was search in the web for time based caching concept in rails.

    We found your article thought provoking, another article i found was

    http://yanpritzker.com/2006/08/19/rails-fragment-cache-with-memcached-client-and-time-based-expire-option/

    http://scottstuff.net/blog/2006/01/20/time-limited-caching-for-rails

    We have a small issue…

    what we are having is a home page with few iframes(with stock data from other websites)

    the loading time is high since data is got from other websites and displayed.

    We would like to cache the page as a pure html and display every say 5 min

    ie the the rails home page is cached and stored as html so the output for normal users will be a plain html page which will be real fast.

    and every 5 min a new cache page is created deleting the old page…

    Could you help us and give an idea how we can achieve them..

    Thanks


Leave a comment


No trackbacks yet.