TimedFileStore Plugin 0.1

My first rails plugin: timed_file_store is now available. It lets you expire fragments based upon the time of the cached file. It’s fairly easy to use; just bung this into config/environments.rb:

  ActionController::Base.fragment_cache_store ="#{RAILS_ROOT}/tmp/cache", :atime => 15.minutes)

And now any fragments which haven’t been accessed in the last 15 minutes will be removed the next time that they’re accessed.

This is rather coarse—it applies to all fragments. But it’s also pretty simple and does what I need for now.


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).