27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

456 CHAPTER 16 Basic performance enhancements<br />

for a file, you shouldn’t see any. The directories (with names like E62 and 3E0) will<br />

still exist, but there aren’t any files. This means that Rails has successfully cleared its<br />

cache of fragments for the project.<br />

Let’s get your sweeper to perform this same action when tickets are updated and<br />

destroyed. Move the expire_fragment call into another method and then call it in the<br />

after_create, after_update, and after_destroy methods in TicketsSweeper using<br />

the code shown in the following listing.<br />

class TicketsSweeper < ActionController::Caching::Sweeper<br />

observe Ticket<br />

def after_create(ticket)<br />

expire_fragments_for_project(ticket.project)<br />

end<br />

end<br />

Listing 16.4 app/sweepers/tickets_sweeper.rb<br />

def after_update(ticket)<br />

expire_fragments_for_project(ticket.project)<br />

end<br />

def after_destroy(ticket)<br />

expire_fragments_for_project(ticket.project)<br />

end<br />

private<br />

def expire_fragments_for_project(project)<br />

expire_fragment(/projects\/#{project.id}\/.*?/)<br />

end<br />

Now you have Rails caching the pages of tickets for all projects in your application and<br />

clearing that cache when tickets are updated. This is a great demonstration of caching<br />

on a per-user basis, even if your project page isn’t that intensive. If you had a system<br />

resource (CPU/memory) intensive action in your application that required user customization<br />

like this, you could use this same method to cache that action to stop it<br />

from being hit so often, which would reduce the strain on your server.<br />

Expiring pages<br />

If you were still using caches_page, you wouldn’t use expire_fragment to expire<br />

the cache files that were generated. Instead, you’d use expire_page, which can take<br />

a hash like this:<br />

expire_page(:controller => "projects",<br />

:action => "show",<br />

:id => 1)<br />

Or, better still would be to pass it the URL helper:<br />

expire_page(project_path(1))<br />

Even though you’re not caching pages any more, it’s still handy to know how to clear<br />

cached pages and fragments.

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

Saved successfully!

Ooh no, something went wrong!