Skip to content

Commit 04529cf

Browse files
authored
Merge pull request #1450 from vlad-pisanov/vp_fix_lexically_scoped_action_filter_2
Fix false positive for `Rails/LexicallyScopedActionFilter` when action methods are delegated
2 parents ec8e18e + 7b92670 commit 04529cf

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1447](https://github.com/rubocop/rubocop-rails/issues/1447): Fix false positive for `Rails/LexicallyScopedActionFilter` when action methods are delegated. ([@vlad-pisanov][])

lib/rubocop/cop/rails/lexically_scoped_action_filter.rb

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,10 @@ class LexicallyScopedActionFilter < Base
115115
$_)))
116116
PATTERN
117117

118+
def_node_matcher :delegated_methods, <<~PATTERN
119+
(send nil? :delegate (sym $_)+ (hash <(pair (sym :to) _) ...>))
120+
PATTERN
121+
118122
def on_send(node)
119123
methods_node = only_or_except_filter_methods(node)
120124
return unless methods_node
@@ -139,7 +143,13 @@ def defined_action_methods(block)
139143
return [] unless block
140144

141145
defined_methods = block.each_child_node(:def).map(&:method_name)
142-
defined_methods + aliased_action_methods(block, defined_methods)
146+
defined_methods + delegated_action_methods(block) + aliased_action_methods(block, defined_methods)
147+
end
148+
149+
def delegated_action_methods(node)
150+
node.each_child_node(:send).flat_map do |child_node|
151+
delegated_methods(child_node) || []
152+
end
143153
end
144154

145155
def aliased_action_methods(node, defined_methods)

spec/rubocop/cop/rails/lexically_scoped_action_filter_spec.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,27 @@ def authorize!
159159
RUBY
160160
end
161161

162+
it 'does not register an offense when action method is delegated' do
163+
expect_no_offenses(<<~RUBY)
164+
class FooController < ApplicationController
165+
before_action :authorize!, only: %i[index show]
166+
167+
delegate :index, :show, to: :foo
168+
end
169+
RUBY
170+
end
171+
172+
it 'registers an offense when action method is not delegated' do
173+
expect_offense(<<~RUBY)
174+
class FooController < ApplicationController
175+
before_action :authorize!, only: %i[foo show]
176+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `foo` is not explicitly defined on the class.
177+
178+
delegate :show, to: :bar
179+
end
180+
RUBY
181+
end
182+
162183
it 'does not register an offense when action method is aliased by `alias`' do
163184
expect_no_offenses(<<~RUBY)
164185
class FooController < ApplicationController

0 commit comments

Comments
 (0)