diff --git a/changelog/fix_autocorrect_for_style_redundant_condition_with_hash.md b/changelog/fix_autocorrect_for_style_redundant_condition_with_hash.md new file mode 100644 index 00000000000..87533203064 --- /dev/null +++ b/changelog/fix_autocorrect_for_style_redundant_condition_with_hash.md @@ -0,0 +1 @@ +* [#10605](https://github.com/rubocop/rubocop/issues/10605): Fix autocorrect for `Style/RedundantCondition` if argument for method in else branch is hash without braces. ([@nobuyo][]) diff --git a/lib/rubocop/cop/style/redundant_condition.rb b/lib/rubocop/cop/style/redundant_condition.rb index 6820261eb43..a3ca00156cd 100644 --- a/lib/rubocop/cop/style/redundant_condition.rb +++ b/lib/rubocop/cop/style/redundant_condition.rb @@ -157,6 +157,8 @@ def else_source(else_branch) def else_source_if_has_method(else_branch) if require_parentheses?(else_branch.first_argument) "(#{else_branch.first_argument.source})" + elsif require_braces?(else_branch.first_argument) + "{ #{else_branch.first_argument.source} }" else else_branch.first_argument.source end @@ -165,6 +167,8 @@ def else_source_if_has_method(else_branch) def else_source_if_has_assignment(else_branch) if require_parentheses?(else_branch.expression) "(#{else_branch.expression.source})" + elsif require_braces?(else_branch.expression) + "{ #{else_branch.expression.source} }" else else_branch.expression.source end @@ -196,6 +200,10 @@ def require_parentheses?(node) (node.respond_to?(:semantic_operator?) && node.semantic_operator?) end + def require_braces?(node) + node.hash_type? && !node.braces? + end + def without_argument_parentheses_method?(node) node.send_type? && !node.arguments.empty? && !node.parenthesized? && !node.operator_method? && !node.assignment_method? diff --git a/spec/rubocop/cop/style/redundant_condition_spec.rb b/spec/rubocop/cop/style/redundant_condition_spec.rb index 6ef3c05d805..88332d42e69 100644 --- a/spec/rubocop/cop/style/redundant_condition_spec.rb +++ b/spec/rubocop/cop/style/redundant_condition_spec.rb @@ -292,6 +292,36 @@ def test RUBY end + it 'registers an offense and corrects when the branches contains method call with braced hash' do + expect_offense(<<~RUBY) + if foo + ^^^^^^ Use double pipes `||` instead. + bar foo + else + bar({ baz => quux }) + end + RUBY + + expect_correction(<<~RUBY) + bar foo || { baz => quux } + RUBY + end + + it 'registers an offense and corrects when the branches contains method call with non-braced hash' do + expect_offense(<<~RUBY) + if foo + ^^^^^^ Use double pipes `||` instead. + bar foo + else + bar baz => quux + end + RUBY + + expect_correction(<<~RUBY) + bar foo || { baz => quux } + RUBY + end + it 'does not register offenses when using `nil?` and the branches contains assignment' do expect_no_offenses(<<~RUBY) if foo.nil?