Prev | Current Page 336 | Next

Brad Ediger

"Advanced Rails"


The first method provided is if_modified, which supports conditional GET. It takes
one or more entities as arguments, which are expected to respond to either the
updated_at or etag methods (or both).??  The updated_at method generates Last-
Modified headers, while the etag method generates an ETag header. Any of these
methods can be overridden or defined on custom entities, depending on the application??™s
idea of ???last update time??? or ???identity.???
This behavior works transparently with ActiveRecord entities. If the ActiveRecord
object has timestamps, its updated_at attribute will be used to provide a Last-Modified
time. The restfully_yours plugin also provides a default etag method that uses an
MD5 hash of either the ActiveRecord ID and lock version if using optimistic locking
(this is a cheap way to get a monotonically increasing version number) or all of its
attributes otherwise. This saves all but the initial trip to the database to get the
attributes and instantiate the ActiveRecord object.
Here is a typical use of this plugin??™s conditional GET functionality:
def show
@product = Product.find params[:id]
if_modified @product do
render
end
end
The if_modified function yields to its block if the provided entity (@product in this
case) has been modified from the client??™s version, as determined by the appropriate
request headers. If the entity has not been modified, a 304 Not Modified response
will be rendered.


Pages:
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348