New Rails Performance Gem: etag_for

January 21, 2013 Link to post  Permalink

In my recent post about HTTP ETags for a faster website, I mentioned at the end that the view template code must be part of the calculation for the ETag value, as it is an integral part of the response. I’ve just released a new ruby gem called etag_for that improves this situation by allowing you to use the Layout and View files, as well as the CSS and Javascript file names, to calculate the ETag value. Now, whenever your view code changes, or you add new Javascript that operates on your generated HTML, then the ETag check will fail, and the user will get the new output, with a new ETag value to allow caching for the next request.

Updating the example in my previous post - note that the JSON code path is unchanged, as this format doesn’t use a layout or view, so doesn’t need them as part of the ETag calculation

def show
    @article = Article.find(params[:id])
    respond_to do |format|
       format.html { 
         fresh_when(:etag => etag_for(@article, :layout => 'application.html.erb', :view => 'article/show.html.erb'), :last_modified => @article.created_at.utc, :public => true)
       }
       format.json {
         if stale?(:etag => @article, :last_modified => @article.created_at.utc, :public => true)
           render :json => @article
         end
       }
    end 
end

The gem can be installed by adding ‘gem “etag_for”’ to your Gemfile

The source code is on Github

The first issue of my Faster Rails Newsletter is due to be released at the end of January. Use the sign up form to the right now to ensure you get it when it is available.