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 a false positive for Style/RedundantCondition #8807

Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -15,6 +15,7 @@
* [#8825](https://github.com/rubocop-hq/rubocop/issues/8825): Fix crash in `Style/ExplicitBlockArgument` when code is called outside of a method. ([@ghiculescu][])
* [#8354](https://github.com/rubocop-hq/rubocop/issues/8354): Detect regexp named captures in `Style/CaseLikeIf` cop. ([@dsavochkin][])
* [#8830](https://github.com/rubocop-hq/rubocop/issues/8830): Fix bad autocorrect of `Style/StringConcatenation` when string includes double quotes. ([@tleish][])
* [#8807](https://github.com/rubocop-hq/rubocop/pull/8807): Fix a false positive for `Style/RedundantCondition` when using assignment by hash key access. ([@koic][])

### Changes

Expand Down
6 changes: 5 additions & 1 deletion lib/rubocop/cop/style/redundant_condition.rb
Expand Up @@ -75,7 +75,7 @@ def range_of_offense(node)
def offense?(node)
condition, if_branch, else_branch = *node

return false if use_if_branch?(else_branch)
return false if use_if_branch?(else_branch) || use_hash_key_assignment?(else_branch)

condition == if_branch && !node.elsif? && (
node.ternary? ||
Expand All @@ -88,6 +88,10 @@ def use_if_branch?(else_branch)
else_branch&.if_type?
end

def use_hash_key_assignment?(else_branch)
else_branch&.send_type? && else_branch&.method?(:[]=)
end

def else_source(else_branch)
if require_parentheses?(else_branch)
"(#{else_branch.source})"
Expand Down
10 changes: 10 additions & 0 deletions spec/rubocop/cop/style/redundant_condition_spec.rb
Expand Up @@ -42,6 +42,16 @@
RUBY
end

it 'registers an offense and corrects when using assignment by hash key access' do
expect_no_offenses(<<~RUBY)
if @cache[key]
@cache[key]
else
@cache[key] = heavy_load[key]
end
RUBY
end

it 'registers an offense and corrects when `raise` without argument parentheses in `else`' do
expect_offense(<<~RUBY)
if b
Expand Down