diff --git a/changelog/fix_infinite_loop_on_style_multiline_ternary_operator.md b/changelog/fix_infinite_loop_on_style_multiline_ternary_operator.md new file mode 100644 index 00000000000..beb0bccf347 --- /dev/null +++ b/changelog/fix_infinite_loop_on_style_multiline_ternary_operator.md @@ -0,0 +1 @@ +* [#10592](https://github.com/rubocop/rubocop/issues/10592): Fix infinite loop on `Style/MultilineTernaryOperator` if using assignment method and condition/branch is multiline. ([@nobuyo][]) diff --git a/lib/rubocop/cop/style/multiline_ternary_operator.rb b/lib/rubocop/cop/style/multiline_ternary_operator.rb index 7d1bdbf57e6..20e993d7888 100644 --- a/lib/rubocop/cop/style/multiline_ternary_operator.rb +++ b/lib/rubocop/cop/style/multiline_ternary_operator.rb @@ -73,7 +73,11 @@ def replacement(node) end def enforce_single_line_ternary_operator?(node) - SINGLE_LINE_TYPES.include?(node.parent.type) + SINGLE_LINE_TYPES.include?(node.parent.type) && !use_assignment_method?(node.parent) + end + + def use_assignment_method?(node) + node.send_type? && node.assignment_method? end 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 30ad1edbef5..29059b00c0c 100644 --- a/spec/rubocop/cop/style/multiline_ternary_operator_spec.rb +++ b/spec/rubocop/cop/style/multiline_ternary_operator_spec.rb @@ -51,6 +51,63 @@ RUBY end + it 'registers an offense and corrects when condition is multiline' do + expect_offense(<<~RUBY) + a = + b == + ^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead. + c ? d : e + RUBY + + expect_correction(<<~RUBY) + a = + if b == + c + d + else + e + end + RUBY + end + + it 'registers an offense and corrects when condition is multiline and using hash key assignment' do + expect_offense(<<~RUBY) + a[:a] = + b == + ^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead. + c ? d : e + RUBY + + expect_correction(<<~RUBY) + a[:a] = + if b == + c + d + else + e + end + RUBY + end + + it 'registers an offense and corrects when condition is multiline and using assignment method' do + expect_offense(<<~RUBY) + a.foo = + b == + ^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead. + c ? d : e + RUBY + + expect_correction(<<~RUBY) + a.foo = + if b == + c + d + else + e + end + RUBY + end + it 'register an offense and corrects when returning a multiline ternary operator expression with `return`' do expect_offense(<<~RUBY) return cond ?