This feature was released in Rails v2.2.1
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):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class ArticlesController < ApplicationController def show @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 block if stale?(:last_modified => @article.published_at.utc, :etag => @article) respond_to do |wants| # ... normal response processing end end # 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:
1 2 3 4 5 6 7 8 9 |
class ArticlesController < 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. def show @article = Article.find(params[:id]) fresh_when :last_modified => @article.published_at.utc, :etag => @article end end |
There you have it, the new and improved conditional GET support in Rails 2.2.
tags: ruby, rubyonrails
