Skip to content

Commit

Permalink
[Fix rubocop#10711] Fix an error for Style/MultilineTernaryOperator
Browse files Browse the repository at this point in the history
Fixes rubocop#10711.

This PR fixes an error for `Style/MultilineTernaryOperator`
when the false branch is on a separate line.
  • Loading branch information
koic committed Jun 13, 2022
1 parent f133b38 commit 04442ec
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#10711](https://github.com/rubocop/rubocop/issues/10711): Fix an error for `Style/MultilineTernaryOperator` when the false branch is on a separate line. ([@koic][])
2 changes: 1 addition & 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,7 @@ def replacement(node)
end

def enforce_single_line_ternary_operator?(node)
SINGLE_LINE_TYPES.include?(node.parent.type) && !use_assignment_method?(node.parent)
SINGLE_LINE_TYPES.include?(node.parent&.type) && !use_assignment_method?(node.parent)
end

def use_assignment_method?(node)
Expand Down
18 changes: 17 additions & 1 deletion spec/rubocop/cop/style/multiline_ternary_operator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
RUBY
end

it 'registers an offense and corrects when the false branch is on a separate line' do
it 'registers an offense and corrects when the false branch is on a separate line and assigning a return value' do
expect_offense(<<~RUBY)
a = cond ? b :
^^^^^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead.
Expand All @@ -34,6 +34,22 @@
RUBY
end

it 'registers an offense and corrects when the false branch is on a separate line' do
expect_offense(<<~RUBY)
cond ? b :
^^^^^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead.
c
RUBY

expect_correction(<<~RUBY)
if cond
b
else
c
end
RUBY
end

it 'registers an offense and corrects when everything is on a separate line' do
expect_offense(<<~RUBY)
a = cond ?
Expand Down

0 comments on commit 04442ec

Please sign in to comment.