Skip to content

Commit 3019c2b

Browse files
committed
[Fix #712] Fixed false negative when visibility modifier is declared in nested class
1 parent 0c18551 commit 3019c2b

File tree

3 files changed

+41
-10
lines changed

3 files changed

+41
-10
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#712](https://github.com/rubocop/rubocop-rails/issues/712): Fix false negative in `Rails/Delegate` when preceding nested class declares private or protected methods. ([@Darhazer][])

lib/rubocop/cop/rails/delegate.rb

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ module Rails
5454
# delegate :bar, to: :foo, prefix: true
5555
class Delegate < Base
5656
extend AutoCorrector
57+
include VisibilityHelp
5758

5859
MSG = 'Use `delegate` to define delegations.'
5960

@@ -112,17 +113,11 @@ def prefixed_method_name(body)
112113
end
113114

114115
def private_or_protected_delegation(node)
115-
line = node.first_line
116-
private_or_protected_before(line) ||
117-
private_or_protected_inline(line)
116+
private_or_protected_inline(node) || node_visibility(node) != :public
118117
end
119118

120-
def private_or_protected_before(line)
121-
(processed_source[0..line].map(&:strip) & %w[private protected]).any?
122-
end
123-
124-
def private_or_protected_inline(line)
125-
processed_source[line - 1].strip.match?(/\A(private )|(protected )/)
119+
def private_or_protected_inline(node)
120+
processed_source[node.first_line - 1].strip.match?(/\A(private )|(protected )/)
126121
end
127122
end
128123
end

spec/rubocop/cop/rails/delegate_spec.rb

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ def fox
125125
bar.fox
126126
end
127127
128-
private
128+
private
129129
130130
def fox
131131
bar.fox
@@ -147,6 +147,41 @@ def fox
147147
RUBY
148148
end
149149

150+
it 'works with private methods declared in inner classes' do
151+
expect_offense(<<~RUBY)
152+
class A
153+
class B
154+
155+
private
156+
157+
def foo
158+
bar.foo
159+
end
160+
end
161+
162+
def baz
163+
^^^ Use `delegate` to define delegations.
164+
foo.baz
165+
end
166+
end
167+
RUBY
168+
169+
expect_correction(<<~RUBY)
170+
class A
171+
class B
172+
173+
private
174+
175+
def foo
176+
bar.foo
177+
end
178+
end
179+
180+
delegate :baz, to: :foo
181+
end
182+
RUBY
183+
end
184+
150185
it 'ignores delegation with assignment' do
151186
expect_no_offenses(<<~RUBY)
152187
def new

0 commit comments

Comments
 (0)