Skip to content

Commit

Permalink
[Fix rubocop#10011] Fix a false positive for `Style/RedundantSelfAssi…
Browse files Browse the repository at this point in the history
…gnmentBranch`

Fixes rubocop#10011.

This PR fixes a false positive for `Style/RedundantSelfAssignmentBranch`
when using instance variable, class variable, and global variable.
  • Loading branch information
koic committed Aug 13, 2021
1 parent cda3f43 commit 33af76d
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 25 deletions.
@@ -0,0 +1 @@
* [#10011](https://github.com/rubocop/rubocop/issues/10011): Fix a false positive for `Style/RedundantSelfAssignmentBranch` when using instance variable, class variable, and global variable. ([@koic][])
7 changes: 3 additions & 4 deletions lib/rubocop/cop/style/redundant_self_assignment_branch.rb
Expand Up @@ -5,6 +5,9 @@ module Cop
module Style
# This cop checks for places where conditional branch makes redundant self-assignment.
#
# It only detects local variable because it may replace state of instance variable,
# class variable, and global variable that have state across methods with `nil`.
#
# @example
#
# # bad
Expand Down Expand Up @@ -45,10 +48,6 @@ def on_lvasgn(node)
end
end

alias on_ivasgn on_lvasgn
alias on_cvasgn on_lvasgn
alias on_gvasgn on_lvasgn

private

def self_assign?(variable, branch)
Expand Down
27 changes: 6 additions & 21 deletions spec/rubocop/cop/style/redundant_self_assignment_branch_spec.rb
Expand Up @@ -125,36 +125,21 @@
RUBY
end

it 'registers and corrects an offense when self-assigning redundant else ternary branch for ivar' do
expect_offense(<<~RUBY)
it 'does not register an offense when self-assigning redundant else ternary branch for ivar' do
expect_no_offenses(<<~RUBY)
@foo = condition ? @bar : @foo
^^^^ Remove the self-assignment branch.
RUBY

expect_correction(<<~RUBY)
@foo = @bar if condition
RUBY
end

it 'registers and corrects an offense when self-assigning redundant else ternary branch for cvar' do
expect_offense(<<~RUBY)
it 'does not register an offense when self-assigning redundant else ternary branch for cvar' do
expect_no_offenses(<<~RUBY)
@@foo = condition ? @@bar : @@foo
^^^^^ Remove the self-assignment branch.
RUBY

expect_correction(<<~RUBY)
@@foo = @@bar if condition
RUBY
end

it 'registers and corrects an offense when self-assigning redundant else ternary branch for gvar' do
expect_offense(<<~RUBY)
it 'does not register an offense when self-assigning redundant else ternary branch for gvar' do
expect_no_offenses(<<~RUBY)
$foo = condition ? $bar : $foo
^^^^ Remove the self-assignment branch.
RUBY

expect_correction(<<~RUBY)
$foo = $bar if condition
RUBY
end

Expand Down

0 comments on commit 33af76d

Please sign in to comment.