Conditional page caching for logged in users
Along with the new design I’ve added some page caching here and there. I’ve yet to do the blog and archives sections, as there seems to be something quirky going on (if you’re aware of any page caching bugs in Rails 2.3.5, let me know :-).
As you may or may not know, this site has a minimal admin section so I can manage content. When I’m logged in, I have an “Admin” tab and a “Logout” link somewhere in the UI. So naturally, I can’t page cache when I’m logged in. Luckily, Rails provides the option to cache on an :if condition.
Here’s a little tip for those in a similar situation:
1 2 3 4 5 6 | class ApplicationController < ActionController::Base protected def self.cache_if_not_logged_in(*actions) self.caches_page *( actions << { :if => Proc.new { |c| !c.send :logged_in? } } ) end end |
Then, in any controller that is to behave this way, all you have to do is:
1 2 3 4 5 6 7 | class PortfolioController < ApplicationController cache_if_not_logged_in :index def index # do what you do best end end |
I know this is rather simple (and to most of you, obvious), but I was once a beginner seeking useful ways to do simple things, so there you go. Chalk one up for the beginners.
