Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix #10592] Fix infinite loop on Style/MultilineTernaryOperator #10594

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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