Skip to content

Commit

Permalink
Fix an incorrect auto-correct for Layout/LineLength
Browse files Browse the repository at this point in the history
This PR fixes the following incorrect auto-correct for `Layout/LineLength`
when a heredoc is used as the first element of an array.

```console
% cat example.rb
[<<~STRING, { key1: value1, key2: value2 }]
STRING

% ruby -c example.rb
Syntax OK

% cat .rubocop.yml
Layout/LineLength:
  Max: 40

% bundle exec rubocop --only Layout/LineLength example.rb -a
(snip)

Inspecting 1 file
C

Offenses:

example.rb:1:41: C: [Corrected] Layout/LineLength: Line is too long. [43/40]
[<<~STRING, { key1: value1, key2: value2 }]
                                        ^^^

1 file inspected, 1 offense detected, 1 offense corrected

% cat example.rb
[<<~STRING,
{ key1: value1, key2: value2 }]
STRING

% ruby -c example.rb
example.rb:1: syntax error, unexpected end-of-input, expecting ']'
```
  • Loading branch information
koic committed Jul 17, 2021
1 parent f2c5f0e commit e1edb41
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
@@ -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][])
4 changes: 2 additions & 2 deletions lib/rubocop/cop/mixin/check_line_breakable.rb
Expand Up @@ -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?

Expand Down
10 changes: 10 additions & 0 deletions spec/rubocop/cop/layout/line_length_spec.rb
Expand Up @@ -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
Expand Down

0 comments on commit e1edb41

Please sign in to comment.