Conditional fragment caching

May 22, 2008

We were just wondering if it’s possible to provide a condition to fragment caching, in order to only cache certain fragments when no user is logged in to our site. This is to ensure anonymous users (the majority of visitors), who will see the same page anyway, will get it loaded from cache. People who log in will see their personalized site.

I was unable to find anything on Google about this, so I wrote my own helper. It looks so obvious that I’m probably not the first to write this, but I figured I’d share it anyway:

  def cache_if (condition, name = {}, &block)
    if condition
      cache(name, &block)

Using this, you can write something like:

<% cache_if @current_user.blank?, 'navigation' do %>
  Navigation content here, including user specific navigation
<% end %>