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
  • Loading branch information
ydah committed Jun 13, 2022
1 parent f133b38 commit cfc797d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
5 changes: 3 additions & 2 deletions lib/rubocop/cop/style/multiline_ternary_operator.rb
Expand Up @@ -7,7 +7,7 @@ module Style
#
# NOTE: `return if ... else ... end` is syntax error. If `return` is used before
# multiline ternary operator expression, it will be autocorrected to single-line
# ternary operator. The same is true for `break`, `next`, and method call.
# ternary operator. The same is true for `break`, `next`, method call, and without assignment.
#
# @example
# # bad
Expand Down Expand Up @@ -73,7 +73,8 @@ def replacement(node)
end

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

def use_assignment_method?(node)
Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/style/multiline_ternary_operator_spec.rb
Expand Up @@ -108,6 +108,18 @@
RUBY
end

it 'register an offense and corrects when returning a multiline ternary operator expression without assignment' do
expect_offense(<<~RUBY)
cond ? foo :
^^^^^^^^^^^^ Avoid multi-line ternary operators, use single-line instead.
bar
RUBY

expect_correction(<<~RUBY)
cond ? foo : bar
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 cfc797d

Please sign in to comment.