Skip to content

Commit

Permalink
[Fix rubocop#12237] Fix Style/NestedTernaryOperator autocorrection
Browse files Browse the repository at this point in the history
Fix autocorrection to correctly support conditionals between nested ternaries.
  • Loading branch information
stevegeek committed Oct 2, 2023
1 parent 2ec14ca commit 3ef6a61
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12237](https://github.com/rubocop/rubocop/issues/12237): Fix `Style/NestedTernaryOperator` autocorrection to support conditionals between nested ternaries. ([@stevegeek][])
2 changes: 1 addition & 1 deletion lib/rubocop/cop/style/nested_ternary_operator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def on_if(node)

def if_node(node)
node = node.parent
return node if node.if_type?
return node if node.if_type? && node.ternary?

if_node(node)
end
Expand Down
19 changes: 19 additions & 0 deletions spec/rubocop/cop/style/nested_ternary_operator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,23 @@
end
RUBY
end

it 'can handle nested ternaries mixed with conditionals' do
expect_offense(<<~RUBY)
a ? (if b
c ? 1 : 2
^^^^^^^^^ Ternary operators must not be nested. Prefer `if` or `else` constructs instead.
end) : 3
RUBY

expect_correction(<<~RUBY)
if a
if b
c ? 1 : 2
end
else
3
end
RUBY
end
end

0 comments on commit 3ef6a61

Please sign in to comment.