27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

460 CHAPTER 16 Basic performance enhancements<br />

You’ve now seen many different flavors of controller caching, ranging from caching<br />

pages and caching actions (actually, fragments), to getting the browser to take care of<br />

the hard part of the caching process (storing a file and expiring it). All of these caching<br />

methods deal with caching entire pages, so what’s a Railer supposed to do if they<br />

want to cache only a bit of a page at a time? For that, you can tell Rails to cache just<br />

these parts using an aptly named method: cache.<br />

16.3.5 Caching page fragments<br />

If part of a page takes a long time to render, then that’s a problem. To fix this kind of<br />

problem, you can use fragment caching, which allows you to cache fragments of pages<br />

using the cache method in your views where appropriate. This method takes a block,<br />

like this:<br />

<br />

# some horribly long and complex thing<br />

<br />

This way, when Rails attempts to load the page and comes across your cache call, it will<br />

check to see if there’s an available fragment for it. Otherwise it will perform the code<br />

inside the block and then store it in tmp/cache, just like caches_action does for an<br />

entire page.<br />

You don’t have an actual use-case for this in your application at the moment, but<br />

you’ll still use it just to see what it does. You’re going to be using it back on the app/<br />

views/projects/show.html.erb view, meaning you’re going to want to temporarily disable<br />

caches_action in ProjectsController for this action so that it doesn’t cache<br />

the page before cache has a chance to run. You can do this by simply removing the<br />

lines in ProjectsController:<br />

# caches_action :show, :cache_path => (proc do<br />

# project_path(params[:id]) + "/#{current_user.id}/#{params[:page] || 1}"<br />

# end)<br />

In the app/views/projects/show.html.erb, the primary content that’s going to be<br />

changing is the list of tickets, and so you’ll want to cache that and leave out the rest.<br />

To do this, you’ll wrap the whole list of tickets, including the pagination link above it,<br />

in a cache block, as shown in the following listing.<br />

Listing 16.5 app/views/projects/show.html.erb<br />

<br />

<br />

<br />

<br />

<br />

<br />

# - <br />

<br />

<br />

<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!