Although this is usually a
bad idea (it expands the total amount of memory required), it can make sense if the
information to be cached is partitioned along application server boundaries.
Fragment cache helper. The most typical use for fragment caching is in caching an
expensive-to-calculate part of a page that must be displayed often. In most cases,
there is other dynamic information on the page (even something as simple as a block
showing the current user??™s login name), so the whole page cannot be cached with
either page caching or action caching.
180 | Chapter 6: Performance
There is a Rails helper for caching part of a page. This helper, called cache, 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. When cache is called, it calls url_for with the arguments given to cache (if
any). This gives the fragment a name like example.com/user/welcome.
Additional options can be given to cache to uniquely identify different fragments
within the same action.
Pages:
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281