From 04442ec4699cc3cdf09abf1351331a7e02155be0 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Mon, 13 Jun 2022 19:09:36 +0900 Subject: [PATCH] [Fix #10711] Fix an error for `Style/MultilineTernaryOperator` Fixes #10711. This PR fixes an error for `Style/MultilineTernaryOperator` when the false branch is on a separate line. --- ...ror_for_style_multiline_ternary_operator.md | 1 + .../cop/style/multiline_ternary_operator.rb | 2 +- .../style/multiline_ternary_operator_spec.rb | 18 +++++++++++++++++- 3 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 changelog/fix_an_error_for_style_multiline_ternary_operator.md diff --git a/changelog/fix_an_error_for_style_multiline_ternary_operator.md b/changelog/fix_an_error_for_style_multiline_ternary_operator.md new file mode 100644 index 00000000000..92f86f3d7cb --- /dev/null +++ b/changelog/fix_an_error_for_style_multiline_ternary_operator.md @@ -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][]) diff --git a/lib/rubocop/cop/style/multiline_ternary_operator.rb b/lib/rubocop/cop/style/multiline_ternary_operator.rb index bfeb1cf8de0..fe769960812 100644 --- a/lib/rubocop/cop/style/multiline_ternary_operator.rb +++ b/lib/rubocop/cop/style/multiline_ternary_operator.rb @@ -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) diff --git a/spec/rubocop/cop/style/multiline_ternary_operator_spec.rb b/spec/rubocop/cop/style/multiline_ternary_operator_spec.rb index 29059b00c0c..1e48855b034 100644 --- a/spec/rubocop/cop/style/multiline_ternary_operator_spec.rb +++ b/spec/rubocop/cop/style/multiline_ternary_operator_spec.rb @@ -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. @@ -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 ?