diff --git a/changelog/fix_incorrect_autocorrect_for_layout_line_length.md b/changelog/fix_incorrect_autocorrect_for_layout_line_length.md new file mode 100644 index 00000000000..3ab5e086fe1 --- /dev/null +++ b/changelog/fix_incorrect_autocorrect_for_layout_line_length.md @@ -0,0 +1 @@ +* [#9938](https://github.com/rubocop/rubocop/pull/9938): Fix an incorrect auto-correct for `Layout/LineLength` when a heredoc is used as the first element of an array. ([@koic][]) diff --git a/lib/rubocop/cop/mixin/check_line_breakable.rb b/lib/rubocop/cop/mixin/check_line_breakable.rb index 7329fe6402a..4297b9e2a56 100644 --- a/lib/rubocop/cop/mixin/check_line_breakable.rb +++ b/lib/rubocop/cop/mixin/check_line_breakable.rb @@ -97,9 +97,9 @@ def first_argument_is_heredoc?(node) # If a send node contains a heredoc argument, splitting cannot happen # after the heredoc or else it will cause a syntax error. def shift_elements_for_heredoc_arg(node, elements, index) - return index unless node.send_type? + return index unless node.send_type? || node.array_type? - heredoc_index = elements.index { |arg| (arg.str_type? || arg.dstr_type?) && arg.heredoc? } + heredoc_index = elements.index { |arg| arg.respond_to?(:heredoc?) && arg.heredoc? } return index unless heredoc_index return nil if heredoc_index.zero? diff --git a/spec/rubocop/cop/layout/line_length_spec.rb b/spec/rubocop/cop/layout/line_length_spec.rb index 5ad3d910af6..29eb59e098c 100644 --- a/spec/rubocop/cop/layout/line_length_spec.rb +++ b/spec/rubocop/cop/layout/line_length_spec.rb @@ -779,6 +779,16 @@ def baz(bar) expect_no_corrections end + it 'does not break up the line when a heredoc is used as the first element of an array' do + expect_offense(<<~RUBY) + [<<~STRING, { key1: value1, key2: value2 }] + ^^^ Line is too long. [43/40] + STRING + RUBY + + expect_no_corrections + end + context 'and other arguments before the heredoc' do it 'can break up the line before the heredoc argument' do args = 'x' * 20