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 %>
Thanks, simple and effective!
Nice, just what I was looking for! :)
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 —