Conditional fragment caching

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)
  else
    yield
  end
end

Using this, you can write something like:

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

3 thoughts on “Conditional fragment caching

  1. Pay attention with Rails 3 Deprecation !
    DEPRECATION WARNING: style block helpers are deprecated. Please use .

    -> If you fix this deprecation-warning by replacing <% with <%=, then you'll end up with twice times the same content!

    better: return nil from the cache_if function as last line
    — cut —
    def cache_if (condition, name = {}, &block)
    if condition
    cache(name, &block)
    else
    yield
    end
    return nil
    end
    — end cut —

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.