diff --git a/changelog/fix_error_for_style_multiline_method_signature.md b/changelog/fix_error_for_style_multiline_method_signature.md new file mode 100644 index 00000000000..d84fdf6c3d0 --- /dev/null +++ b/changelog/fix_error_for_style_multiline_method_signature.md @@ -0,0 +1 @@ +* [#9644](https://github.com/rubocop/rubocop/pull/9644): Fix an error and an incorrect auto-correct for `Style/MultilineMethodSignature` when line break after opening parenthesis. ([@koic][]) diff --git a/lib/rubocop/cop/style/multiline_method_signature.rb b/lib/rubocop/cop/style/multiline_method_signature.rb index 566b2a7808a..f1e0dc5191a 100644 --- a/lib/rubocop/cop/style/multiline_method_signature.rb +++ b/lib/rubocop/cop/style/multiline_method_signature.rb @@ -40,7 +40,7 @@ def on_def(node) def autocorrect(corrector, node) arguments = node.arguments joined_arguments = arguments.map(&:source).join(', ') - last_line_source_of_arguments = processed_source[arguments.last_line - 1].strip + last_line_source_of_arguments = last_line_source_of_arguments(arguments) if last_line_source_of_arguments.start_with?(')') joined_arguments = "#{joined_arguments}#{last_line_source_of_arguments}" @@ -48,13 +48,20 @@ def autocorrect(corrector, node) corrector.remove(range_by_whole_lines(arguments.loc.end, include_final_newline: true)) end - corrector.replace(arguments_range(node), joined_arguments) + corrector.remove(arguments_range(node)) + corrector.insert_after(arguments.loc.begin, joined_arguments) + end + + def last_line_source_of_arguments(arguments) + processed_source[arguments.last_line - 1].strip end def arguments_range(node) - range_between( + range = range_between( node.first_argument.source_range.begin_pos, node.last_argument.source_range.end_pos ) + + range_with_surrounding_space(range: range, side: :left) end def opening_line(node) diff --git a/spec/rubocop/cop/style/multiline_method_signature_spec.rb b/spec/rubocop/cop/style/multiline_method_signature_spec.rb index 470f36885a4..3eeb6ab9741 100644 --- a/spec/rubocop/cop/style/multiline_method_signature_spec.rb +++ b/spec/rubocop/cop/style/multiline_method_signature_spec.rb @@ -17,6 +17,25 @@ def foo(bar) RUBY end + it 'registers an offense and corrects when line break after opening parenthesis' do + expect_offense(<<~RUBY) + class Foo + def foo( + ^^^^^^^^ Avoid multi-line method signatures. + arg + ) + end + end + RUBY + + expect_correction(<<~RUBY) + class Foo + def foo(arg) + end + end + RUBY + end + context 'when method signature is on a single line' do it 'does not register an offense for parameterized method' do expect_no_offenses(<<~RUBY)