Skip to content

Commit

Permalink
[Fix rubocop#12237] Fix an error for Style/NestedTernaryOperator
Browse files Browse the repository at this point in the history
Fixes rubocop#12237.

This PR fixes an error for `Style/NestedTernaryOperator`
when a ternary operator has a nested ternary operator within an `if`.
  • Loading branch information
koic committed Oct 2, 2023
1 parent 2ec14ca commit 5344c78
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 11 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12237](https://github.com/rubocop/rubocop/issues/12237): Fix an error for `Style/NestedTernaryOperator` when a ternary operator has a nested ternary operator within an `if`. ([@koic][])
14 changes: 3 additions & 11 deletions lib/rubocop/cop/style/nested_ternary_operator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,16 @@ def on_if(node)

node.each_descendant(:if).select(&:ternary?).each do |nested_ternary|
add_offense(nested_ternary) do |corrector|
if_node = if_node(nested_ternary)
next if part_of_ignored_node?(if_node)
next if part_of_ignored_node?(node)

autocorrect(corrector, if_node)
ignore_node(if_node)
autocorrect(corrector, node)
ignore_node(node)
end
end
end

private

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

if_node(node)
end

def autocorrect(corrector, if_node)
replace_loc_and_whitespace(corrector, if_node.loc.question, "\n")
replace_loc_and_whitespace(corrector, if_node.loc.colon, "\nelse\n")
Expand Down
23 changes: 23 additions & 0 deletions spec/rubocop/cop/style/nested_ternary_operator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,29 @@
RUBY
end

it 'registers an offense when a ternary operator has a nested ternary operator within an `if`' 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

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

0 comments on commit 5344c78

Please sign in to comment.