From f588088cb602e1d72a77b30037ea213243a7649d Mon Sep 17 00:00:00 2001 From: Daniel Vandersluis Date: Sun, 10 Jan 2021 12:17:00 -0500 Subject: [PATCH] [Fix #9355] Fix `Style/SingleLineMethods` autocorrection to endless method when the original code had parens. --- changelog/fix_fix_stylesinglelinemethods.md | 1 + lib/rubocop/cop/style/single_line_methods.rb | 3 ++- spec/rubocop/cop/style/single_line_methods_spec.rb | 12 ++++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_fix_stylesinglelinemethods.md diff --git a/changelog/fix_fix_stylesinglelinemethods.md b/changelog/fix_fix_stylesinglelinemethods.md new file mode 100644 index 000000000000..31726085432f --- /dev/null +++ b/changelog/fix_fix_stylesinglelinemethods.md @@ -0,0 +1 @@ +* [#9355](https://github.com/rubocop-hq/rubocop/issues/9355): Fix `Style/SingleLineMethods` autocorrection to endless method when the original code had parens. ([@dvandersluis][]) diff --git a/lib/rubocop/cop/style/single_line_methods.rb b/lib/rubocop/cop/style/single_line_methods.rb index f5cd13cbed86..57e1d3f40f40 100644 --- a/lib/rubocop/cop/style/single_line_methods.rb +++ b/lib/rubocop/cop/style/single_line_methods.rb @@ -89,7 +89,8 @@ def correct_to_multiline(corrector, node) end def correct_to_endless(corrector, node) - replacement = "def #{node.method_name}(#{node.arguments.source}) = #{node.body.source}" + arguments = node.arguments.any? ? node.arguments.source : '()' + replacement = "def #{node.method_name}#{arguments} = #{node.body.source}" corrector.replace(node, replacement) end diff --git a/spec/rubocop/cop/style/single_line_methods_spec.rb b/spec/rubocop/cop/style/single_line_methods_spec.rb index b18b8b22e4d2..30138cd70f28 100644 --- a/spec/rubocop/cop/style/single_line_methods_spec.rb +++ b/spec/rubocop/cop/style/single_line_methods_spec.rb @@ -176,6 +176,18 @@ def some_method() = body # comment RUBY end + it 'handles arguments properly' do + expect_correction(<<~RUBY.strip, source: 'def some_method(a, b, c) body end') + def some_method(a, b, c) = body + RUBY + end + + it 'does not add parens if they are already present' do + expect_correction(<<~RUBY.strip, source: 'def some_method() body end') + def some_method() = body + RUBY + end + it 'does not correct to an endless method if the method body contains multiple statements' do expect_correction(<<~RUBY.strip, source: 'def some_method; foo; bar end') def some_method;#{trailing_whitespace}