02 Mar, 2010

Published at 12:24PM

Tagged with caching, programming, rails, and tips

This post has 0 comments

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.

Comments

Do you have something to say about this post?
Retype the image to the right Spam Hint: Are You Human? Textile Formatting Tips

or

Ryan Heath | Site Management A Ruby on Rails production.

This site is a Formed Function. Formed Function LLC | @formedfunction | Get in Touch