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.

458 CHAPTER 16 Basic performance enhancements<br />

1. Request comes in for<br />

GET /projects/1/tickets/2<br />

with If-None-Match header set to "ef2"<br />

2. Trickles down...<br />

3. ... to the controller<br />

Browser<br />

Web Server<br />

Application<br />

Controller<br />

Even though this goes through the same series of events both times, what happens in<br />

the controller is the clincher: by returning a 304 Not Modified, you can respond with<br />

a lightweight response and get the user’s browser to render the page, rather than having<br />

your application do it again.<br />

For your ticket page, you’re going to want your application to send back this status<br />

only when your ticket hasn’t been updated. When a ticket’s information such as the<br />

title or description is updated, or when a comment is posted to the ticket, you’d want<br />

to send back a proper response rather than the 304 Not Modified header. It’s this<br />

timestamp that you’re going to be using to determine if a page is either fresh or stale.<br />

A fresh page is one that’s been recently updated, with a stale page being one that<br />

hasn’t been.<br />

You’ve got a column in your tickets table that you can use to determine if a<br />

ticket’s been updated: the updated_at column. Each time a ticket’s updated through<br />

your application, this field will be set to the timestamp automatically. But, when a<br />

comment is posted to the ticket, the updated_at field for the ticket will remain the<br />

same.<br />

To fix this problem, you can configure the Comment model to touch the ticket<br />

object it’s related to, which will update its updated_at timestamp. The way you do this<br />

is with an option on the belongs_to association in Comment called touch. Let’s change<br />

the belongs_to :ticket line currently in app/models/comment.rb to this:<br />

belongs_to :ticket, :touch => true<br />

6. Browser knows to<br />

use its local cache<br />

5. Bubbles up<br />

through the stack<br />

4. Controller recognizes ETag,<br />

sends back a<br />

ed status<br />

Figure 16.11<br />

304 Not Modified<br />

response<br />

Whenever a comment is updated, created, or even destroyed, the related ticket’s<br />

updated_at attribute will be updated. With the touch option, you can now confidently<br />

use this attribute to provide a reliable timestamp for your new form of caching. This<br />

particular form of caching uses a new method in your controllers called fresh_when.

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

Saved successfully!

Ooh no, something went wrong!