I was going through the AWDR book on web development with ruby on rails and one of the issues with the old code was it didn’t use respond_to to make sure the view used would be the javascript view. Now in some updated examples I’ve seen people mention they later, when implementing graceful degradation, use request.xhr? to tell if the user has javascript enabled, and if not they redirect the user.
I was wondering if you could use respond_to to get the same behaviour and if so, if this is considered good form or not and why?
So what I’m thinking of doing is something like:
def function respond_to do |format| format.js do basic_stuff end format.html do basic_stuff user_redirect end end end
It does seem to sorta violate the DRY principle, and I’m probably missing something about how the user and the server are interacting here. To be honest the API documentation did not make it entirely clear to me.
Well you can refactor like this:
request.xhr?looks at the request‘sX-Requested-Withheader (to see whether it contains ‘XMLHttpRequest’).respond_tolooks at the mime types accepted.You can use either to implement some sort of graceful degredation.
BUT You won’t be able to use
xhr?for graceful degredation unless your ajax calls are setting that header (Prototype does this automatically).Moreover,
respond_togives more flexibility i.e. sending xml, json, js, whatever it might be from the same block.So I’d recommend
respond_tohere.