All three of these classes contain methods that wrap around content in
your templates. BenchmarkHelper
is a
class you’ll mostly want to use during development, when it may help you
isolate code that’s taking the view a long time to run. CacheHelper
and CaptureHelper
are both
for advanced development. While CacheHelper
allows you to specify fragments of your
views that will be stored for future reuse, and applied when the same
call comes through, CaptureHelper
lets you manually grab content that needs to be used again in the same
view, probably to share content from the template with the
layout:
benchmark
The benchmark
method
takes an optional message argument and an optional logging level argument (:debug
, :info
, :warn
, or :error
). It records how long the wrapped
code takes to run. It requires a block argument, so it usually
looks something like:
<% benchmark "It took this long:" do %> <%= my_long_method %> <% end % >
The message and the length of time it takes to run will end up in the logs.
cache
The cache
method lets
you flag fragments of your view to be kept for caching. Like
benchmark
, cache
wraps around the view code it’s
meant to work on with a block argument:
<% cache do %> <%= my_repetitive_method_that_should_be_cached %> <% end % >
You should only cache information that doesn’t change very often, but many HTML components are pretty stable.
capture
The capture
method
wraps around view code and stores its output to a variable. You
can then reference the variable and have that content appear
wherever you need. In operation, it looks like a variable
assignment to a method:
<% @trapped_content = capture do %> <%= content_to_put_in_there %> <% end % >
Once you’ve captured it, you can reference @trapped_content
wherever it is convenient.
content_for
The content_for
method is much like capture
,
but instead of putting the content in a variable, it lets you
create a named block you can yield
to in order to include the
content.