I needed to expire caches using jobs. If I used an observer or a sweeper the updates would happen to often. I was displaying the info of a bunch of records (foobars) on a single view and I didn’t want it to update every time a Foobar was created – that would be too often and reduce the benefits of caching.
Instead I wanted a job that ran every hour to expire the cache.
- First, I installed the Whenever gem which updates the cron file and helping you schedule server jobs.
- use the command `wheneverize .` to generate the schedule.rb file for Whenever
- I created a new rake file, “expire_cache.rake” in lib/tasks
- In the file, I put this:task :expire_cache_1_hour => :environment do
puts “———————expiring 1 hour cache————-”
ActionController::Base.new.expire_fragment(“foobar”) #I already had <% cache(‘foobar’) do %> in my view
- In the schedule.rb file used by Whenever, I added:every 1.hour do
I wanted to figure out how much Memcache memory I was using for my Heroku Rails app. After all, how would I know if I need to upgrade otherwise, unless I keep checking the logs for the word ‘miss’.
I found out through this post on Stackoverflow.
From the console (‘heroku run console’ with the Cedar stack), enter
it will provide a bunch of stats, and towards the end you will see bytes.
I was having trouble expiring a cache from a model. When I tried just: expire_fragment, I received an error.
I luckily found this post by Michael Mahemoff and found the syntax I needed:
To learn about caching, I used a few different resources.
The three basic types of caching are:
- page caching – mainly for static pages, it will not work if any filters are applied to the controller of the page (ie authorizations)
- action caching – typically what you’d used to cache a page if they have filters
- fragment caching – allows for caching of blocks of html on a page (if you can’t cache the whole page) or for partials
Since I’m on Heroku, the first place to learn was Heroku’s documentation. It’s important to read the Heroku docs first because some standard Rails functions work differently on Heroku’ platform. Mainly, for page caching (uses different syntax than standard rails) and action caching (mostly dependent on memcache, so you need to set your app up accordingly).
Overview of caching on Heroku
There’s also a Rails Guide on Caching (just remember to ignore page caching part):
However, the most extensive (and useful) one for me was from Adam Hawkins at (especially for fragment caching):
I also needed to learn about sweepers, in order to observe for changes that would impact another controller’s pages. This Stack Overflow post helped me learn to put the sweeper in with the models and to ensure that I updated the correct controller: