Categories
Uncategorized

Rails Fragment Cache Expiry

I’ve been looking at Rails’ fragment caching recently. I want to cache some stuff in my view that’s more or less independent of my model (eg: output from some slow command like top). That’s fine, and easily done.

  <% cache do %>
    <%=h `top` %>
  <% end %>

The trouble is expiry (as it always is with caching). By default, Rails offers you things like expire_fragment and Sweeping, but these are very much tied in to the Model classes.

What I really need is to know the timestamp of each entry in the cache, so I can make judgements based on that. Unfortunately, at present, ActionController seems to treat each cache entry as little more than a blob of data. I need to store metadata with it, like when it was last accessed and when it was put in the cache. I’m not sure that I can do that in the current framework.

It looks like I’m not the only one who wants this: see also Time-based fragment caching in Rails. I’m not 100% sure I like that solution, but it does look like it would work. Perhaps I’m too institutionalized towards cron? I’d definitely rather avoid using cron if I can possibly help it (lesson from work: system dependencies are bad).

2 replies on “Rails Fragment Cache Expiry”

We use a mix of time-based fragment caching (that we essentially borrowed from Typo) and rails_cron for longer running and less frequently needed tasks (it could also do cache expiration). Using the “metafragment” approach you can store anything you can read/write with yaml, so you can store any other needed metadata besides just expiration time. But there is a little more coordination involved.

The nice part about rails_cron is that the overhead of starting up rails is done once, but it’s scheduling isn’t as flexible as real cron (can’t say “run at 6am on Sundays”).

Leave a Reply to mike Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s