Skip to content

Commit 12b45a5

Browse files
authored
Merge pull request #1448 from ydakuka/1446/fix-incorrect-autocorrect-for-rails-delegate-when-module_function-is-used
[Fix #1446] Fix false positives for `Rails/Delegate` when `module_function` is used
2 parents f943057 + 204e667 commit 12b45a5

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1446](https://github.com/rubocop/rubocop-rails/issues/1446): Fix false positives for `Rails/Delegate` when `module_function` is used. ([@ydakuka][])

lib/rubocop/cop/rails/delegate.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ class Delegate < Base
7474
def on_def(node)
7575
return unless trivial_delegate?(node)
7676
return if private_or_protected_delegation(node)
77+
return if module_function_declared?(node)
7778

7879
register_offense(node)
7980
end
@@ -163,6 +164,12 @@ def private_or_protected_delegation(node)
163164
private_or_protected_inline(node) || node_visibility(node) != :public
164165
end
165166

167+
def module_function_declared?(node)
168+
node.each_ancestor(:module, :begin).any? do |ancestor|
169+
ancestor.children.any? { |child| child.send_type? && child.method?(:module_function) }
170+
end
171+
end
172+
166173
def private_or_protected_inline(node)
167174
processed_source[node.first_line - 1].strip.match?(/\A(private )|(protected )/)
168175
end

spec/rubocop/cop/rails/delegate_spec.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,28 @@ def foo
4242
RUBY
4343
end
4444

45+
it 'does not find trivial delegate to `self` for separate `module_function` def' do
46+
expect_no_offenses(<<~RUBY)
47+
module A
48+
module_function
49+
50+
def foo
51+
self.foo
52+
end
53+
end
54+
RUBY
55+
end
56+
57+
it 'does not find trivial delegate to `self` for inline `module_function` def' do
58+
expect_no_offenses(<<~RUBY)
59+
module A
60+
module_function def foo
61+
self.foo
62+
end
63+
end
64+
RUBY
65+
end
66+
4567
it 'finds trivial delegate with prefix' do
4668
expect_offense(<<~RUBY)
4769
def bar_foo

0 commit comments

Comments
 (0)