diff --git a/changelog/new_autocorrect_wraps_method_definitions.md b/changelog/new_autocorrect_wraps_method_definitions.md new file mode 100644 index 00000000000..60bf83f71e3 --- /dev/null +++ b/changelog/new_autocorrect_wraps_method_definitions.md @@ -0,0 +1 @@ +* [#10692](https://github.com/rubocop/rubocop/pull/10692): Break long method definitions when auto-correcting. ([@Korri][]) diff --git a/lib/rubocop/cop/layout/line_length.rb b/lib/rubocop/cop/layout/line_length.rb index 51912d1906f..0b1d2866bb1 100644 --- a/lib/rubocop/cop/layout/line_length.rb +++ b/lib/rubocop/cop/layout/line_length.rb @@ -80,6 +80,7 @@ def on_potential_breakable_node(node) alias on_array on_potential_breakable_node alias on_hash on_potential_breakable_node alias on_send on_potential_breakable_node + alias on_def on_potential_breakable_node def on_new_investigation check_for_breakable_semicolons(processed_source) diff --git a/lib/rubocop/cop/mixin/check_line_breakable.rb b/lib/rubocop/cop/mixin/check_line_breakable.rb index 4297b9e2a56..b6fdb4d804c 100644 --- a/lib/rubocop/cop/mixin/check_line_breakable.rb +++ b/lib/rubocop/cop/mixin/check_line_breakable.rb @@ -46,6 +46,8 @@ def extract_breakable_node(node, max) if node.send_type? args = process_args(node.arguments) return extract_breakable_node_from_elements(node, args, max) + elsif node.def_type? + return extract_breakable_node_from_elements(node, node.arguments, max) elsif node.array_type? || node.hash_type? return extract_breakable_node_from_elements(node, node.children, max) end @@ -216,6 +218,8 @@ def process_args(args) # @api private def already_on_multiple_lines?(node) + return node.first_line != node.arguments.last.last_line if node.def_type? + node.first_line != node.last_line end end diff --git a/spec/rubocop/cop/layout/line_length_spec.rb b/spec/rubocop/cop/layout/line_length_spec.rb index f8a61b77fe8..ecf519c7345 100644 --- a/spec/rubocop/cop/layout/line_length_spec.rb +++ b/spec/rubocop/cop/layout/line_length_spec.rb @@ -597,6 +597,32 @@ def method_definition_that_is_just_under_the_line_length_limit(foo) # rubocop:di end end + context 'method definition' do + context 'when under limit' do + it 'does not add any offenses' do + expect_no_offenses(<<~RUBY) + def foo(foo: 1, bar: "2"); end + RUBY + end + end + + context 'when over limit' do + it 'adds an offense and autocorrects it' do + expect_offense(<<~RUBY) + def foo(abc: "100000", def: "100000", ghi: "100000", jkl: "100000", mno: "100000") + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Line is too long. [82/40] + end + RUBY + + expect_correction(<<~RUBY) + def foo(abc: "100000", def: "100000",#{trailing_whitespace} + ghi: "100000", jkl: "100000", mno: "100000") + end + RUBY + end + end + end + context 'method call' do context 'when under limit' do it 'does not add any offenses' do