Skip to content

Commit

Permalink
[Fix rubocop#10592] Fix infinite loop on `Style/MultilineTernaryOpera…
Browse files Browse the repository at this point in the history
…tor` if using assignment method and condition/branch is multiline

Update lib/rubocop/cop/style/multiline_ternary_operator.rb

Co-authored-by: Koichi ITO <koic.ito@gmail.com>
  • Loading branch information
nobuyo and koic committed Apr 30, 2022
1 parent 793f145 commit 153b651
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 1 deletion.
@@ -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][])
6 changes: 5 additions & 1 deletion lib/rubocop/cop/style/multiline_ternary_operator.rb
Expand Up @@ -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
Expand Down
57 changes: 57 additions & 0 deletions spec/rubocop/cop/style/multiline_ternary_operator_spec.rb
Expand Up @@ -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 ?
Expand Down

0 comments on commit 153b651

Please sign in to comment.