diff --git a/changelog/fix_error_for_style_multiline_ternary_operator.md b/changelog/fix_error_for_style_multiline_ternary_operator.md new file mode 100644 index 000000000000..d95c296446c1 --- /dev/null +++ b/changelog/fix_error_for_style_multiline_ternary_operator.md @@ -0,0 +1 @@ +* [#12691](https://github.com/rubocop/rubocop/issues/12691): Fix an error for `Style/MultilineTernaryOperator` when nesting multiline ternary operators. ([@koic][]) diff --git a/lib/rubocop/cop/style/multiline_ternary_operator.rb b/lib/rubocop/cop/style/multiline_ternary_operator.rb index 23a656eed724..03ec44f3eede 100644 --- a/lib/rubocop/cop/style/multiline_ternary_operator.rb +++ b/lib/rubocop/cop/style/multiline_ternary_operator.rb @@ -47,7 +47,11 @@ def on_if(node) message = enforce_single_line_ternary_operator?(node) ? MSG_SINGLE_LINE : MSG_IF add_offense(node, message: message) do |corrector| + next if part_of_ignored_node?(node) + autocorrect(corrector, node) + + ignore_node(node) end end diff --git a/spec/rubocop/cop/style/multiline_ternary_operator_spec.rb b/spec/rubocop/cop/style/multiline_ternary_operator_spec.rb index 51848de34cf2..0f23c97d3486 100644 --- a/spec/rubocop/cop/style/multiline_ternary_operator_spec.rb +++ b/spec/rubocop/cop/style/multiline_ternary_operator_spec.rb @@ -50,6 +50,28 @@ RUBY end + it 'registers an offense and corrects when nesting multiline ternary operators' do + expect_offense(<<~RUBY) + cond_a? ? foo : + ^^^^^^^^^^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead. + cond_b? ? bar : + ^^^^^^^^^^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead. + cond_c? ? baz : qux + RUBY + + expect_correction(<<~RUBY) + if cond_a? + foo + else + if cond_b? + bar + else + cond_c? ? baz : qux + end + end + RUBY + end + it 'registers an offense and corrects when everything is on a separate line' do expect_offense(<<~RUBY) a = cond ?