Skip to content

Commit

Permalink
[Fix #11634] Tweak autocorrection for Style/ConcatArrayLiterals
Browse files Browse the repository at this point in the history
Fixes #11634.

This PR tweaks autocorrection for `Style/ConcatArrayLiterals`
when using `concat` with multiline multiple elements array literal argument.

Percent literal arguments have not been tweaked because implementation complexity.
  • Loading branch information
koic authored and bbatsov committed Feb 27, 2023
1 parent cde4bc2 commit c651ffa
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/rubocop/cop/style/concat_array_literals.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def on_send(node)
offense = offense_range(node)
current = offense.source

if node.arguments.any?(&:percent_literal?)
if (use_percent_literal = node.arguments.any?(&:percent_literal?))
if percent_literals_includes_only_basic_literals?(node)
prefer = preferred_method(node)
message = format(MSG, prefer: prefer, current: current)
Expand All @@ -51,7 +51,15 @@ def on_send(node)
end

add_offense(offense, message: message) do |corrector|
corrector.replace(offense, prefer)
if use_percent_literal
corrector.replace(offense, prefer)
else
corrector.replace(node.loc.selector, 'push')
node.arguments.each do |argument|
corrector.remove(argument.loc.begin)
corrector.remove(argument.loc.end)
end
end
end
end
# rubocop:enable Metrics
Expand Down
17 changes: 17 additions & 0 deletions spec/rubocop/cop/style/concat_array_literals_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,23 @@
RUBY
end

it 'registers an offense when using `concat` with multiline multiple elements array literal argument' do
expect_offense(<<~RUBY)
arr.concat([
^^^^^^^^ Use `push(foo, bar)` instead of `concat([[...]
foo,
bar
])
RUBY

expect_correction(<<~RUBY)
arr.push(
foo,
bar
)
RUBY
end

it 'registers an offense when using `concat` with multiple array literal arguments' do
expect_offense(<<~RUBY)
arr.concat([foo, bar], [baz])
Expand Down

0 comments on commit c651ffa

Please sign in to comment.