This post originated from an RSS feed registered with Ruby Buzz
by rwdaigle.
Original Post: What's New in Edge Rails: Even Better Conditional GET Support
Feed Title: Ryan's Scraps
Feed URL: http://feeds.feedburner.com/RyansScraps
Feed Description: Ryan Daigle's various technically inclined rants along w/ the "What's new in Edge Rails" series.
We talked about the new conditional GET support in rails a couple months ago. As some of the comments alluded, the feature was somewhat cumbersome to use – especially by Ruby standards. Well, the feature has since been refined. So, read the original post to get the gist and come back here for the sugar.
Instead of manually setting properties directly on the response and querying the request to see if it’s fresh we have some higher-level accessors we can use. Observe (extending our previous example):
123456789101112131415161718
classArticlesController < ApplicationControllerdefshow@article = Article.find(params[:id])# If the request is stale according to the given timestamp and etag value# (i.e. it needs to be processed again) then execute this blockif stale?(:last_modified => @article.published_at.utc, :etag => @article) respond_to do |wants|# ... normal response processingendend# If the request is fresh (i.e. it's not modified) then you don't need to do# anything. The default render checks for this using the parameters# used in the previous call to stale? and will automatically send a# :not_modified. So that's it, you're done.end
If you don’t have any special response processing and are using the default rendering mechanism (i.e. you’re not using respond_to or calling render yourself) then you’ve got an easy helper in fresh_when:
123456789
classArticlesController < ApplicationController# This will automatically send back a :not_modified if the request is fresh, and# will render the default template (article.*) if it's stale.defshow@article = Article.find(params[:id]) fresh_when :last_modified => @article.published_at.utc, :etag => @articleendend
There you have it, the new and improved conditional GET support in Rails 2.2.