Skip to content

Commit

Permalink
Merge pull request #736 from rubocop/fix-false-negative-in-rails-dele…
Browse files Browse the repository at this point in the history
…gate

[Fix #712] Fixed false negative when visibility modifier is declared in nested class
  • Loading branch information
koic committed Jul 5, 2022
2 parents a703aaf + 3019c2b commit 990a786
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 10 deletions.
@@ -0,0 +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][])
13 changes: 4 additions & 9 deletions lib/rubocop/cop/rails/delegate.rb
Expand Up @@ -54,6 +54,7 @@ module Rails
# delegate :bar, to: :foo, prefix: true
class Delegate < Base
extend AutoCorrector
include VisibilityHelp

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

Expand Down Expand Up @@ -112,17 +113,11 @@ def prefixed_method_name(body)
end

def private_or_protected_delegation(node)
line = node.first_line
private_or_protected_before(line) ||
private_or_protected_inline(line)
private_or_protected_inline(node) || node_visibility(node) != :public
end

def private_or_protected_before(line)
(processed_source[0..line].map(&:strip) & %w[private protected]).any?
end

def private_or_protected_inline(line)
processed_source[line - 1].strip.match?(/\A(private )|(protected )/)
def private_or_protected_inline(node)
processed_source[node.first_line - 1].strip.match?(/\A(private )|(protected )/)
end
end
end
Expand Down
37 changes: 36 additions & 1 deletion spec/rubocop/cop/rails/delegate_spec.rb
Expand Up @@ -125,7 +125,7 @@ def fox
bar.fox
end
private
private
def fox
bar.fox
Expand All @@ -147,6 +147,41 @@ def fox
RUBY
end

it 'works with private methods declared in inner classes' do
expect_offense(<<~RUBY)
class A
class B
private
def foo
bar.foo
end
end
def baz
^^^ Use `delegate` to define delegations.
foo.baz
end
end
RUBY

expect_correction(<<~RUBY)
class A
class B
private
def foo
bar.foo
end
end
delegate :baz, to: :foo
end
RUBY
end

it 'ignores delegation with assignment' do
expect_no_offenses(<<~RUBY)
def new
Expand Down

0 comments on commit 990a786

Please sign in to comment.