Go rails caching!
I had no idea caching is SO simple in rails. I added some caching to thecollegestuff.com. Two places where caching was clearly needed were the college page listing all its professors and the professor page with all the ratings. Majority of the people who land on these pages are only viewing these pages. They are not really adding content. So, it makes sense to fetch the page quickly (from the cache).
For now the way my cache expires is when someone rates a professor in which case I expire that professor page. Similarly, I expire the college page when a new professor is added. Below is a code snippet which does the caching.
class ProfessorsController < ApplicationController
caches_page :show
cache_sweeper :professor_sweeper,
nly => [ :create ]
caches_page is self explanatory. I have cached the show transaction.
cache_sweeper is used to expire the cache when a create method is called on the professor. Below is the sweeper code.
class ProfessorSweeper < ActionController::Caching::Sweeper
observe Professor
def after_create(professor)
expire_college_page(profesor.college_id)
end
private
def expire_college_page(collegeId)
expire_page :controller => “colleges”, :action => “show”, :id => collegeId
end
end
That is all it takes to do a page caching! I am sure I can find more places in my code which can be cached. I will have to see if I can use some action caching or fragment caching somewhere. The home page has the top professor and college list which are database queries. I have to find a nice way to cache that part of the page. I will play around next weekend. Have a good week!
Cheers,
Mahesh