Skip to content

Commit

Permalink
[Fix rubocop#12731] Treat csend the same way as send for setter methods
Browse files Browse the repository at this point in the history
In order to detect code like `if test&.method = 10` we need to find not only
send nodes but also csend nodes.
  • Loading branch information
jonas054 committed Mar 23, 2024
1 parent b2062d5 commit 43c8986
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog/fix_assignment_in_condition_safe_nav_setter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12731](https://github.com/rubocop/rubocop/pull/12731): Treat `&.` the same way as `.` for setter methods in `Lint/AssignmentInCondition`. ([@jonas054][])
2 changes: 1 addition & 1 deletion lib/rubocop/cop/lint/assignment_in_condition.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class AssignmentInCondition < Base
MSG_WITHOUT_SAFE_ASSIGNMENT_ALLOWED =
'Use `==` if you meant to do a comparison or move the assignment ' \
'up out of the condition.'
ASGN_TYPES = [:begin, *AST::Node::EQUALS_ASSIGNMENTS, :send].freeze
ASGN_TYPES = [:begin, *AST::Node::EQUALS_ASSIGNMENTS, :send, :csend].freeze

def on_if(node)
return if node.condition.block_type?
Expand Down
2 changes: 1 addition & 1 deletion lib/rubocop/cop/mixin/safe_assignment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ module SafeAssignment
def_node_matcher :empty_condition?, '(begin)'

# @!method setter_method?(node)
def_node_matcher :setter_method?, '[(send ...) setter_method?]'
def_node_matcher :setter_method?, '[({send csend} ...) setter_method?]'

# @!method safe_assignment?(node)
def_node_matcher :safe_assignment?, '(begin {equals_asgn? #setter_method?})'
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/lint/assignment_in_condition_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,19 @@
RUBY
end

it 'registers an offense for assignment methods with safe navigation operator' do
expect_offense(<<~RUBY)
if test&.method = 10
^ Use `==` if you meant to do a comparison or wrap the expression in parentheses to indicate you meant to assign in a condition.
end
RUBY

expect_correction(<<~RUBY)
if (test&.method = 10)
end
RUBY
end

it 'does not blow up for empty if condition' do
expect_no_offenses(<<~RUBY)
if ()
Expand Down

0 comments on commit 43c8986

Please sign in to comment.