forked from rubocop/rubocop-rails
/
ignored_skip_action_filter_option.rb
96 lines (85 loc) · 2.86 KB
/
ignored_skip_action_filter_option.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# This cop checks that `if` and `only` (or `except`) are not used together
# as options of `skip_*` action filter.
#
# The `if` option will be ignored when `if` and `only` are used together.
# Similarly, the `except` option will be ignored when `if` and `except`
# are used together.
#
# @example
# # bad
# class MyPageController < ApplicationController
# skip_before_action :login_required,
# only: :show, if: :trusted_origin?
# end
#
# # good
# class MyPageController < ApplicationController
# skip_before_action :login_required,
# if: -> { trusted_origin? && action_name == "show" }
# end
#
# @example
# # bad
# class MyPageController < ApplicationController
# skip_before_action :login_required,
# except: :admin, if: :trusted_origin?
# end
#
# # good
# class MyPageController < ApplicationController
# skip_before_action :login_required,
# if: -> { trusted_origin? && action_name != "admin" }
# end
#
# @see https://api.rubyonrails.org/classes/AbstractController/Callbacks/ClassMethods.html#method-i-_normalize_callback_options
class IgnoredSkipActionFilterOption < Cop
MSG = <<~MSG.chomp.freeze
`%<ignore>s` option will be ignored when `%<prefer>s` and `%<ignore>s` are used together.
MSG
RESTRICT_ON_SEND = %i[
skip_after_action
skip_around_action
skip_before_action
skip_action_callback
].freeze
FILTERS = RESTRICT_ON_SEND.map { |method_name| ":#{method_name}" }
def_node_matcher :filter_options, <<~PATTERN
(send
nil?
{#{FILTERS.join(' ')}}
_
$_)
PATTERN
def on_send(node)
options = filter_options(node)
return unless options
return unless options.hash_type?
options = options_hash(options)
if if_and_only?(options)
add_offense(options[:if],
message: format(MSG, prefer: :only, ignore: :if))
elsif if_and_except?(options)
add_offense(options[:except],
message: format(MSG, prefer: :if, ignore: :except))
end
end
private
def options_hash(options)
options.pairs
.select { |pair| pair.key.sym_type? }
.map { |pair| [pair.key.value, pair] }.to_h
end
def if_and_only?(options)
options.key?(:if) && options.key?(:only)
end
def if_and_except?(options)
options.key?(:if) && options.key?(:except)
end
end
end
end
end