Module: Controllers::ReturnPathHandling

Extended by:
ActiveSupport::Concern
Included in:
ApplicationController
Defined in:
app/concerns/controllers/return_path_handling.rb

Overview

Return path handling for preserving navigation context

Parses and validates return_path parameter, allowing users to be
redirected back to where they came from after completing an action.

Usage:

In views - pass return path in links

link_to 'Edit', edit_path(return_path: request.fullpath)

In controller - redirect back

redirect_to_return_path_or_default(fallback_path)

Instance variables set:
@return_path - The validated URL to return to
@return_title - Optional title for the return link

Instance Method Summary collapse

Instance Method Details

#check_for_return_pathvoid (protected)

This method returns an undefined value.

Parse return_path parameter and set instance variables.

Uses Rails's built-in url_from to validate the URL: returns the URL
only if it's on the same host as the request, nil otherwise. This
is real open-redirect protection, not just parse-validity (which is
what the previous Addressable::URI.parse rescue dance gave us).



32
33
34
35
36
37
# File 'app/concerns/controllers/return_path_handling.rb', line 32

protected def check_for_return_path
  return if json_request?

  @return_path = url_from(params[:return_path]).presence
  @return_title = params[:return_title].presence
end

#redirect_to_return_path_or_default(default, options = {}) ⇒ void (protected)

This method returns an undefined value.

Redirect to return path or fall back to default.

Parameters:

  • default (String)

    The fallback path if no return_path is set

  • options (Hash) (defaults to: {})

    Additional redirect options

Options Hash (options):

  • status (Symbol, Integer)

    HTTP status for the redirect
    (defaults to 302 Found)

  • allow_other_host (Boolean)

    allow redirecting to a host
    other than the request host



48
49
50
# File 'app/concerns/controllers/return_path_handling.rb', line 48

protected def redirect_to_return_path_or_default(default, options = {})
  redirect_to(@return_path || default, options)
end