Skip to content

Commit

Permalink
Merge pull request rubocop#12604 from koic/fix_a_false_positive_for_s…
Browse files Browse the repository at this point in the history
…tyle_multiline_ternary_operator

[Fix rubocop#12603] Fix an infinite loop error for `Style/MultilineTernaryOperator`
  • Loading branch information
koic committed Jan 10, 2024
2 parents 753a82c + 4d058aa commit 5cd23f8
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 3 deletions.
@@ -0,0 +1 @@
* [#12603](https://github.com/rubocop/rubocop/issues/12603): Fix an infinite loop error for `Style/MultilineTernaryOperator` when using a method call as a ternary operator condition with a line break between receiver and method. ([@koic][])
4 changes: 1 addition & 3 deletions lib/rubocop/cop/style/multiline_ternary_operator.rb
Expand Up @@ -54,12 +54,10 @@ def on_if(node)
private

def offense?(node)
node.ternary? && node.multiline?
node.ternary? && node.multiline? && node.source != replacement(node)
end

def autocorrect(corrector, node)
return unless offense?(node)

corrector.replace(node, replacement(node))
return unless (parent = node.parent)
return unless (comments_in_condition = comments_in_condition(node))
Expand Down
15 changes: 15 additions & 0 deletions spec/rubocop/cli/autocorrect_spec.rb
Expand Up @@ -2971,6 +2971,21 @@ module Foo#{trailing_whitespace}
RUBY
end

it 'does not cause an infinite loop error for `Style/MultilineTernaryOperator`' do
source_file = Pathname('example.rb')
create_file(source_file, <<~RUBY)
do_something(arg
.foo ? bar : baz)
RUBY

status = cli.run(%w[--autocorrect-all --only Style/MultilineTernaryOperator])
expect(status).to eq(0)
expect(source_file.read).to eq(<<~RUBY)
do_something(arg
.foo ? bar : baz)
RUBY
end

it 'respects `Lint/ConstantResolution` over `Style/RedundantConstantBase` when enabling`Lint/ConstantResolution`' do
source_file = Pathname('example.rb')
create_file(source_file, <<~RUBY)
Expand Down
9 changes: 9 additions & 0 deletions spec/rubocop/cop/style/multiline_ternary_operator_spec.rb
Expand Up @@ -124,6 +124,15 @@
RUBY
end

it 'does not register an offense when using a method call as a ternary operator condition with a line break ' \
'between receiver and method' do
# NOTE: Redundant line break is corrected by `Layout/RedundantLineBreak`.
expect_no_offenses(<<~RUBY)
do_something(arg
.foo ? bar : baz)
RUBY
end

it 'registers 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 5cd23f8

Please sign in to comment.