Class: RuboCop::Cop::Heatwave::PreferRedirectBackOrTo

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/heatwave/prefer_redirect_back_or_to.rb

Overview

Flags Rails' deprecated redirect_back fallback_location: x form and
rewrites it to the modern redirect_back_or_to(x) API.

redirect_back is deprecated in Rails 7.0 and slated for removal.
redirect_back_or_to accepts the fallback as a positional argument
and otherwise behaves identically (including the
ApplicationController#redirect_to 303-on-write override).

Examples:

# bad
redirect_back fallback_location: root_path
redirect_back fallback_location: thing_path(@thing), alert: 'No'

# good
redirect_back_or_to root_path
redirect_back_or_to thing_path(@thing), alert: 'No'

Constant Summary collapse

MSG =
'`redirect_back` is deprecated in Rails 7.0 — use ' \
'`redirect_back_or_to(fallback)` instead.'

Instance Method Summary collapse

Instance Method Details

#fallback_location_pair(node) ⇒ Object



34
35
36
# File 'lib/rubocop/cop/heatwave/prefer_redirect_back_or_to.rb', line 34

def_node_matcher :fallback_location_pair, <<~PATTERN
  (pair (sym :fallback_location) $_)
PATTERN

#on_send(node) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rubocop/cop/heatwave/prefer_redirect_back_or_to.rb', line 38

def on_send(node)
  args = redirect_back_call(node)
  return unless args

  hash_arg = args.last
  return unless hash_arg.is_a?(RuboCop::AST::HashNode)

  fallback_pair = hash_arg.pairs.find { |pair| fallback_location_pair(pair) }
  return unless fallback_pair

  fallback_value = fallback_location_pair(fallback_pair)
  rest_pairs = hash_arg.pairs - [fallback_pair]

  new_args = +fallback_value.source
  new_args << ', ' << rest_pairs.map(&:source).join(', ') unless rest_pairs.empty?
  replacement = "redirect_back_or_to #{new_args}"

  add_offense(node) do |corrector|
    corrector.replace(node, replacement)
  end
end

#redirect_back_call(node) ⇒ Object



29
30
31
# File 'lib/rubocop/cop/heatwave/prefer_redirect_back_or_to.rb', line 29

def_node_matcher :redirect_back_call, <<~PATTERN
  (send nil? :redirect_back $...)
PATTERN