Skip to content

Commit

Permalink
Break long method definitions when auto-correcting
Browse files Browse the repository at this point in the history
This allows rubocop to autocorrect method definitions by wrapping them
on multiple lines when they violate the `Layout/LineLength` rule by
adding method definition logic inside `CheckLineBreakable`.
  • Loading branch information
Korri authored and bbatsov committed Jul 13, 2022
1 parent 0562314 commit 8d484e3
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions 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][])
1 change: 1 addition & 0 deletions lib/rubocop/cop/layout/line_length.rb
Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions lib/rubocop/cop/mixin/check_line_breakable.rb
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
26 changes: 26 additions & 0 deletions spec/rubocop/cop/layout/line_length_spec.rb
Expand Up @@ -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
Expand Down

0 comments on commit 8d484e3

Please sign in to comment.