Holding current rails location for future redirection

I always have this problem of redirects not going back to the exact page that I want it to. After chatting with some of the rails developers at #rubyonrails on freenode, they’ve provided me with this handy code snipplet to save the current page location temporary and after redirecting it, destroy that temporary location.

We can return to this location by calling #redirect_back_or_default.

def hold_location
 session[:return_to] = request.request_uri
end

# Redirect to the URI stored by the most recent hold_location call or
# to the passed default. Set an appropriately modified
#   after_filter :hold_location, :only => [:index, :new, :show, :edit]
# for any controller you want to be bounce-backable.

def redirect_back_or_default(default)
  redirect_to(session[:return_to] || default)
  session[:return_to] = nil
end

Put this in your ApplicationController and you can just call a hold_location method call anywhere in your code and do a simple redirection later with a redirect_back_or_default call. Cheers.