Skip to content

Commit

Permalink
[Fix rubocop#8821] Fix an incorrect autocorrect for `Style/NestedTern…
Browse files Browse the repository at this point in the history
…aryOperator`

Fixes rubocop#8821

This PR fixes an incorrect autocorrect for `Style/NestedTernaryOperator` when
using a nested ternary operator expression with no parentheses on the outside.
  • Loading branch information
koic committed Oct 2, 2020
1 parent 04b9f9e commit 77e4659
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -14,6 +14,7 @@
* [#8514](https://github.com/rubocop-hq/rubocop/issues/8514): Correct multiple `Style/MethodDefParentheses` per file. ([@rdunlop][])
* [#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][])
* [#8821](https://github.com/rubocop-hq/rubocop/issues/8821): Fix an incorrect autocorrect for `Style/NestedTernaryOperator` when using a nested ternary operator expression with no parentheses on the outside. ([@koic][])

### Changes

Expand Down
2 changes: 2 additions & 0 deletions lib/rubocop/cop/style/nested_ternary_operator.rb
Expand Up @@ -49,6 +49,8 @@ def if_node(node)
end

def remove_parentheses(source)
return source unless source.start_with?('(')

source.gsub(/\A\(/, '').gsub(/\)\z/, '')
end
end
Expand Down
15 changes: 15 additions & 0 deletions spec/rubocop/cop/style/nested_ternary_operator_spec.rb
Expand Up @@ -34,6 +34,21 @@
RUBY
end

it 'registers an offense and corrects for a nested ternary operator expression with no parentheses on the outside' do
expect_offense(<<~RUBY)
x ? y + (z ? 1 : 0) : nil
^^^^^^^^^ Ternary operators must not be nested. Prefer `if` or `else` constructs instead.
RUBY

expect_correction(<<~RUBY)
if x
y + (z ? 1 : 0)
else
nil
end
RUBY
end

it 'accepts a non-nested ternary operator within an if' do
expect_no_offenses(<<~RUBY)
a = if x
Expand Down

0 comments on commit 77e4659

Please sign in to comment.