Skip to content

Commit

Permalink
[Fix rubocop#12434] Fix a false positive for `Lint/LiteralAssignmentI…
Browse files Browse the repository at this point in the history
…nCondition`

Fixes rubocop#12434.

This PR fixes a false positive for `Lint/LiteralAssignmentInCondition`
when using interpolated string or xstring literals.
  • Loading branch information
koic committed Dec 2, 2023
1 parent 2e4ca82 commit fbe1761
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12434](https://github.com/rubocop/rubocop/issues/12434): Fix a false positive for `Lint/LiteralAssignmentInCondition` when using interpolated string or xstring literals. ([@koic][])
6 changes: 4 additions & 2 deletions lib/rubocop/cop/lint/literal_assignment_in_condition.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def on_if(node)
next unless asgn_node.loc.operator

rhs = asgn_node.to_a.last
next if !literal?(rhs) || parallel_assignment_with_splat_operator?(rhs)
next if !forbidden_literal?(rhs) || parallel_assignment_with_splat_operator?(rhs)

range = offense_range(asgn_node, rhs)

Expand All @@ -59,7 +59,9 @@ def traverse_node(node, &block)
node.each_child_node { |child| traverse_node(child, &block) }
end

def literal?(node)
def forbidden_literal?(node)
return false if node.dstr_type? || node.xstr_type?

node.respond_to?(:literal?) && node.literal?
end

Expand Down
22 changes: 22 additions & 0 deletions spec/rubocop/cop/lint/literal_assignment_in_condition_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,28 @@
RUBY
end

it 'registers an offense when assigning string literal to local variable in `if` condition' do
expect_offense(<<~RUBY)
if test = 'foo'
^^^^^^^ Don't use literal assignment `= 'foo'` in conditional, should be `==` or non-literal operand.
end
RUBY
end

it 'does not register an offense when assigning interpolated string literal to local variable in `if` condition' do
expect_no_offenses(<<~'RUBY')
if test = "#{foo}"
end
RUBY
end

it 'does not register an offense when assigning xstring literal to local variable in `if` condition' do
expect_no_offenses(<<~RUBY)
if test = `echo 'hi'`
end
RUBY
end

it 'registers an offense when assigning array literal to local variable in `if` condition' do
expect_offense(<<~RUBY)
if test = []
Expand Down

0 comments on commit fbe1761

Please sign in to comment.