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.

Page and action caching<br />

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

project_path(params[:id], :user_id => current_user.id)<br />

end)<br />

Here, you’ve passed the cache_path option to caches_action. This is a proc object,<br />

and you need to wrap the value for this option in brackets or Ruby will think the block<br />

is for the caches_action call.<br />

This Proc object is evaluated within the context of an instance of this controller,<br />

and therefore you’ll have access to the params and current_user methods usually<br />

available within an action or a before_filter. With these, you’re building a string by<br />

combining the URL of the current project (provided to you by the helper<br />

project_path) and the id of current_user.<br />

When you access this page again in the browser, Rails will re-process this action<br />

because the cache path has changed and then save the page in a new location. In<br />

the output for the server you’ll see this new fragment has been written, indicated by<br />

this line:<br />

Write fragment views/localhost:3000/projects/1/1 (4.4ms)<br />

This time, the path to the file and the file itself have changed because you’ve changed<br />

the URL of the page; it’s now the cached version of this page currently for this user.<br />

When you sign out as your current user and sign in as the other user and navigate to<br />

this project’s page, you’ll see that the “Signed in” message at the top of the page is<br />

now the correct one, as shown in figure 16.9.<br />

This means that you’ve now fixed the problem where the same cached page was<br />

shown for all users, meaning that each of your users will see a slightly different version<br />

of this page. This is almost right, but not quite. When you click the Next link for pagination,<br />

you’ll still only be shown the first page. This is because much like<br />

caches_page, your caches_action also ignores the page parameter.<br />

You can fix this, however, by changing the path generated for the cached page to<br />

contain the current page number. To do this, change this line in caches_action’s<br />

cache_path option in ProjectsController<br />

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

Figure 16.9 Signed in as<br />

admin for a cached page<br />

453

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

Saved successfully!

Ooh no, something went wrong!