posted on Thursday, June 24, 2010
Simple fragment caching example:
<% cache do %>
Something here ...
<% end %>
Or if you want to specify action name and suffix of this cache block:
<% cache(:action => 'index', :action_suffix => 'all') do %>
Something here ...
<% end %>
Maybe it's not the best way to handle cached fragment names but i prefer using this kind of key:
<% cache('top#posts#') do %>
top posts block content ...
<% end %>
where 'top' is just a key of this cached fragment, but #posts# is used as identifier for the type of content, so for example we have 3 cached blocks, and they are not related to one controller or action:
When new post was created or deleted, instead of specifying expire_fragment for each cache key, you just add one line to your sweeper or observer or wherever you specify your expiring:
expire_fragment %r{#posts#}
And after that all cached blocks that related to posts are expired, its usefull when you have lots of fragments which are loaded from different controllers and actions and placed all over the website. The result of this is you'll never mess up with key names of your fragments, and will be sure that your cache is always up to date.
Continue reading