Skip to content

Instantly share code, notes, and snippets.

@sunny
Created June 18, 2015 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunny/bf20cf2d8bc935321e9d to your computer and use it in GitHub Desktop.
Save sunny/bf20cf2d8bc935321e9d to your computer and use it in GitHub Desktop.
# This concern helps controllers redirect to the previous page by storing in session
# the current GET request.
#
# On controllers that need to redirect or that you don't want to keep track of, use:
# skip_before_action :store_previous_url
#
# And then you can redirect to `session[:previous_url]` or use the
# `redirect_to_previous_or_root` helper.
#
# Also, this catches exceptions thrown by `redirect_to :back` when there is
# no referrer by redirecting to the latest GET request.
module PreviousableController
extend ActiveSupport::Concern
included do
# This is not an after_action because authentication redirects usually
# halt the callback chain.
before_action :store_previous_url
# Catch redirect_to :back
rescue_from ActionController::RedirectBackError,
with: :redirect_to_previous_or_root
end
protected
def store_previous_url
session[:previous_url] = request.fullpath if request.get?
end
def redirect_to_previous_or_root
redirect_to session[:previous_url] || root_url
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment