Conditional GET

I have to admit this . I always fall in love with RAILS each day as I explore it to know how a complex problem can be handle with great ease and with minimum amount of code.

That what made me write this post on " Conditional Get Request."
For those who aren’t aware of it let me give them some insight in it.

Conditional GETs are a feature of the HTTP specification that provide a way for web servers to tell browsers that the response to a GET request hasn’t changed since the last request and can be safely pulled from the browser cache.

They work by using the HTTP_IF_NONE_MATCH and HTTP_IF_MODIFIED_SINCE headers to pass back and forth both a unique content identifier and thetimestamp of when the content was last changed. If the browser makes a request where the content identifier (etag) or last modified since timestamp matches the server’s version then the server only needs to send back an empty response with a not modified status.

Enough of talk now its  time for the action (Way to achieve it in Rails)

class UsersController < ApplicationController
 def show
   @user = User.find(params[:id])
    fresh_when :last_modified => @user.last_updated_at ,:etag => @user
 end
end

That it done

Now let check the logs to find, does it actually asking browser to read from its cache.

First time the page will completely render but any subsequent query for the same page will ask the browser to display from its cache(browser cache) (until modified).

Here my log :-
Conditional GET-Log
Other way to achieve the same is.

 def show
   @user = User.find(param[:id])
    if stale?(:last_modified_at => @user.updated_at,:etag => @user)
      repsond_to do |format|
        format.html
      end
    end
end
 def show
   @user = User.find(params[:id])
    response.last_modified = @user.updated_at
    response.etag = @user
    if request.fresh?(response)
      head :not_modified
    else
      respond_to do |format|
        format.html
      end
    end
 end

The Following Code should give you same result as above

That it , thats all it take to get " Conditional GET " working in Rails. Wasn’t I right when I said that I fall in love with Rails each day.

Usage :-

Now most of you  might be wondering where can they employ this technique or when should they use it

My Answer to them is think of Conditional Get a kind of Caching Mechanism ( after that what browser is doing for you)

Now suppose you have a method in controller that make large number of Database queries or ERB template that render a lot of contents on per requests .Wrapping the same with " Conditional GET " can simply do a lot of good.

That it enough on " Conditional GET " . Hope the post help you in some way or other.

Thank You .

5 comments On Conditional GET

Leave a reply:

Your email address will not be published.

Site Footer