Skip to content

Commit

Permalink
Merge pull request #10606 from nobuyo/fix-autocorrect-for-style-redun…
Browse files Browse the repository at this point in the history
…dant-condition-with-hash

[Fix #10605] Fix autocorrect for `Style/RedundantCondition`
  • Loading branch information
koic committed May 7, 2022
2 parents 4643ff3 + e7885d0 commit 3531610
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
@@ -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][])
8 changes: 8 additions & 0 deletions lib/rubocop/cop/style/redundant_condition.rb
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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?
Expand Down
30 changes: 30 additions & 0 deletions spec/rubocop/cop/style/redundant_condition_spec.rb
Expand Up @@ -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?
Expand Down

0 comments on commit 3531610

Please sign in to comment.