Class: Rubocop::Cop::RedirectWithStatus

Inherits:
RuboCop::Cop::Base
  • Object
show all
Defined in:
lib/rubocop/cop/redirect_with_status.rb

Overview

Prevents usage of ‘redirect_to’ in actions ‘destroy’ and ‘destroy_all’ without specifying ‘status’.

See gitlab.com/gitlab-org/gitlab-ce/issues/31840

Examples:

# bad

def destroy
  redirect_to root_path
end

def destroy_all
  redirect_to root_path, alert: 'Oh no!'
end

# good

def destroy
  redirect_to root_path, status: 302
end

def destroy_all
  redirect_to root_path, alert: 'Oh no!', status: 302
end

def show
  redirect_to root_path
end

Constant Summary collapse

MSG =
'Do not use "redirect_to" without "status" in "%<name>s" action.'
RESTRICT_ON_SEND =
%i[redirect_to].freeze
ACTIONS =
%i[destroy destroy_all].to_set.freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'lib/rubocop/cop/redirect_with_status.rb', line 48

def on_send(node)
  return if redirect_to_with_status?(node)

  node.each_ancestor(:def) do |def_node|
    next unless ACTIONS.include?(def_node.method_name)

    message = format(MSG, name: def_node.method_name)
    add_offense(node.loc.selector, message: message)
  end
end

#redirect_to_with_status?(node) ⇒ Object



42
43
44
45
46
# File 'lib/rubocop/cop/redirect_with_status.rb', line 42

def_node_matcher :redirect_to_with_status?, <<~PATTERN
  (send nil? :redirect_to ...
    (hash <(pair (sym :status) _) ...>)
  )
PATTERN