Using respond_to for graceful degradation with ajax in RoR 2.x
-
02-07-2019 - |
Question
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.
Solution
Well you can refactor like this:
def function
basic_stuff # executed regardless of the mime types accepted
respond_to do |format|
format.html do
user_redirect
end
end
# will fall back rendering the default view - which you should ensure will be js
end
request.xhr?
looks at the request‘s X-Requested-With
header (to see whether it contains "XMLHttpRequest"). respond_to
looks 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_to
gives more flexibility i.e. sending xml, json, js, whatever it might be from the same block.
So I'd recommend respond_to
here.