In a recent project I found myself writing recirect_to :back
alot, and then found myself worrying that what if for some reason there is no :back
.
Drawing inspiration from this blog, I wrote two helpers in my application_controller.rb
.
The store_location stores current URI (or referer URI in case of non-GET request) into session[:return_to]
for later usage:
#!ruby
def store_location
session[:return_to] = if request.get?
request.request_uri
else
request.referer
end
end
And redirect_back_or_default tries its best to redirect the user to somewhere, in the following order:
- previously stored
session[:return_to]
- Referer URI
- Given default URI
- or
root_url
if all else fails
The code itself
#!ruby
def redirect_back_or_default(default = root_url, options)
redirect_to(session.delete(:return_to) || request.referer || default, options)
end
I’ve found that when rewriting redirect_to :back, notice: 'something'
into redirect_back_or_default
-call, adding this alias helps:
#!ruby
alias_method :redirect_to_back_or_default, :redirect_back_or_default
But of course, if you are testing your code (and you should be), it’s better to stick to one variant of above and use tests to catch all erroneous incarnations.