From 8a4ee257d75cacf22e3ad5db6635d017248980a5 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Sat, 27 Feb 2021 01:10:18 +0900 Subject: [PATCH] Fix a false positive for `Style/TrailingBodyOnMethodDefinition` This PR fixes a false positive for `Style/TrailingBodyOnMethodDefinition` when endless method definition body is after newline in opening parenthesis. --- ...ive_for_style_trailing_body_on_method_definition.md | 1 + .../cop/style/trailing_body_on_method_definition.rb | 1 + .../style/trailing_body_on_method_definition_spec.rb | 10 ++++++++++ 3 files changed, 12 insertions(+) create mode 100644 changelog/fix_false_positive_for_style_trailing_body_on_method_definition.md diff --git a/changelog/fix_false_positive_for_style_trailing_body_on_method_definition.md b/changelog/fix_false_positive_for_style_trailing_body_on_method_definition.md new file mode 100644 index 00000000000..ad38b97bd46 --- /dev/null +++ b/changelog/fix_false_positive_for_style_trailing_body_on_method_definition.md @@ -0,0 +1 @@ +* [#9548](https://github.com/rubocop/rubocop/pull/9548): Fix a false positive for `Style/TrailingBodyOnMethodDefinition` when endless method definition body is after newline in opening parenthesis. ([@koic][]) diff --git a/lib/rubocop/cop/style/trailing_body_on_method_definition.rb b/lib/rubocop/cop/style/trailing_body_on_method_definition.rb index 107b642ac7d..db07398292e 100644 --- a/lib/rubocop/cop/style/trailing_body_on_method_definition.rb +++ b/lib/rubocop/cop/style/trailing_body_on_method_definition.rb @@ -34,6 +34,7 @@ class TrailingBodyOnMethodDefinition < Base def on_def(node) return unless trailing_body?(node) + return if node.endless? && node.body.parenthesized_call? add_offense(first_part_of(node.body)) do |corrector| LineBreakCorrector.correct_trailing_body( diff --git a/spec/rubocop/cop/style/trailing_body_on_method_definition_spec.rb b/spec/rubocop/cop/style/trailing_body_on_method_definition_spec.rb index 9458efa0baa..1e49a787893 100644 --- a/spec/rubocop/cop/style/trailing_body_on_method_definition_spec.rb +++ b/spec/rubocop/cop/style/trailing_body_on_method_definition_spec.rb @@ -91,6 +91,16 @@ def some_method RUBY end + context 'Ruby 3.0 or higher', :ruby30 do + it 'does not register offense when endless method definition body is after newline in opening parenthesis' do + expect_no_offenses(<<~RUBY) + def some_method = ( + body + ) + RUBY + end + end + it 'auto-corrects with comment after body' do expect_offense(<<-RUBY.strip_margin('|')) | def some_method; body # stuff