Skip to content

Commit 9d1a400

Browse files
authored
Merge pull request #1100 from vlad-pisanov/vp_fix_lexically_scoped_action_filter
[Fix #1078] Fix false negative for `Rails/LexicallyScopedActionFilter`
2 parents 8e43737 + eb76249 commit 9d1a400

File tree

3 files changed

+17
-8
lines changed

3 files changed

+17
-8
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1078](https://github.com/rubocop/rubocop-rails/issues/1078): Fix a false negative for `Rails/LexicallyScopedActionFilter` when no methods are defined. ([@vlad-pisanov][])

lib/rubocop/cop/rails/lexically_scoped_action_filter.rb

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -122,24 +122,23 @@ def on_send(node)
122122
parent = node.each_ancestor(:class, :module).first
123123
return unless parent
124124

125+
# NOTE: a `:begin` node may not exist if the class/module consists of a single statement
125126
block = parent.each_child_node(:begin).first
126-
return unless block
127-
128127
defined_action_methods = defined_action_methods(block)
129128

130-
methods = array_values(methods_node).reject do |method|
131-
defined_action_methods.include?(method)
132-
end
129+
unmatched_methods = array_values(methods_node) - defined_action_methods
130+
return if unmatched_methods.empty?
133131

134-
message = message(methods, parent)
135-
add_offense(node, message: message) unless methods.empty?
132+
message = message(unmatched_methods, parent)
133+
add_offense(node, message: message)
136134
end
137135

138136
private
139137

140138
def defined_action_methods(block)
141-
defined_methods = block.each_child_node(:def).map(&:method_name)
139+
return [] unless block
142140

141+
defined_methods = block.each_child_node(:def).map(&:method_name)
143142
defined_methods + aliased_action_methods(block, defined_methods)
144143
end
145144

spec/rubocop/cop/rails/lexically_scoped_action_filter_spec.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,15 @@ def index
4949
RUBY
5050
end
5151

52+
it 'registers an offense when no methods are defined' do
53+
expect_offense <<~RUBY
54+
class LoginController < ApplicationController
55+
before_action :require_login, only: %i[index show]
56+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `index`, `show` are not explicitly defined on the class.
57+
end
58+
RUBY
59+
end
60+
5261
it 'register an offense when using action filter in module' do
5362
expect_offense <<~RUBY
5463
module FooMixin

0 commit comments

Comments
 (0)