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.