Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix #10605] Fix autocorrect for Style/RedundantCondition #10606

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -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