180 | Chapter 6: Performance
There is a Rails helper for caching part of a page. This helper, calledcache, abstracts
away the details of writing to the cache and checking it. The simplest scenario, where
there is at most one cached block per page, looks like this:
Welcome, <%=h @username %>.
<% cache do %>
The prime factors of 1693371614173 are
<%=h 1693371614173.prime_factors.to_sentence %>.
<% end %>
The fragment cache store is presented as a hashtable. Fragments are stored by a
string key. The default key scheme uses the path of the current action to index the
hash. Whencacheis called, it callsurl_forwith the arguments given tocache(if
any). This gives the fragment a name likeexample.com/user/welcome.
Additional options can be given tocacheto uniquely identify different fragments
within the same action. These options will be passed through tourl_for. In particu-
lar, you can use this to differentiate between two or more cached fragments on the
same page:
<% cache(:id => 'one') do %>
This is cached as example.com/some/action/one.
<% end %>
<% cache(:id => 'two') do %>
This is cached as example.com/some/action/two.
<% end %>
Theurl_forfunction is only used here to provide a unique name for the cached frag-
ment; it does not need to map to a real-world route. But sticking to these conven-
tions (the real action name plus an optional action suffix) will avoid collisions with
names of unrelated fragments.
Fragment expiration.The expirefragment method removes a fragment from the
cache. It takes either a string or a hash argument, in the same format as thewrite
fragmentandcachemethods. If passed a hash, it will run it throughurl_forand
delete the appropriate items from the cache.
Alternatively,expire_fragmentcan take a regular expression as an argument, and it
will delete all pages with keys matching that regexp. This is not recommended. That
syntax is not supported with memcached (which cannot iterate over its keys), and for
all other fragment cache stores, Rails must iterate over every key and check it against
the regular expression. This can slow things down tremendously.
Cache sweepers
As discussed before, cache sweepers are model observers that expire cached pages,
actions, and fragments when their model objects change. Sweepers inherit from
ActionController::Caching::Sweeper and implement the standard callback methods.