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 %>
Advertisements

3 Responses to Conditional fragment caching

  1. Michael says:

    Thanks, simple and effective!

  2. Julie says:

    Nice, just what I was looking for! :)

  3. jan says:

    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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: