Skip to content

Commit

Permalink
[Fix rubocop#12683] Fix an incorrect autocorrect for `Style/MapCompac…
Browse files Browse the repository at this point in the history
…tWithConditionalBlock`

Fixes rubocop#12683

This PR fixes an incorrect autocorrect for `Style/MapCompactWithConditionalBlock`
when using guard clause with `next` implicitly nil. It also fixes the incorrect test code.
  • Loading branch information
koic committed Feb 13, 2024
1 parent 1dac6a4 commit 29c47f8
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 10 deletions.
@@ -0,0 +1 @@
* [#12683](https://github.com/rubocop/rubocop/issues/12683): Fix an incorrect autocorrect for `Style/MapCompactWithConditionalBlock` when using guard clause with `next` implicitly nil. ([@koic][])
8 changes: 4 additions & 4 deletions lib/rubocop/cop/style/map_compact_with_conditional_block.rb
Expand Up @@ -116,10 +116,10 @@ def truthy_branch_for_if?(node)
def truthy_branch_for_guard?(node)
if_node = node.left_sibling

if if_node.if? || if_node.ternary?
if_node.else_branch.nil?
elsif if_node.unless?
if_node.if_branch.nil?
if if_node.if?
if_node.if_branch.arguments.any?
else
if_node.if_branch.arguments.none?
end
end

Expand Down
Expand Up @@ -158,33 +158,33 @@
RUBY
end

it 'registers an offense and corrects to `select` with guard clause of `if`' do
it 'registers an offense and corrects to `reject` with guard clause of `if`' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
next if item.bar?
item
end.compact
RUBY

expect_correction <<~RUBY
foo.select { |item| item.bar? }
foo.reject { |item| item.bar? }
RUBY
end

it 'registers an offense and corrects to `reject` with guard clause of `unless`' do
it 'registers an offense and corrects to `select` with guard clause of `unless`' do
expect_offense(<<~RUBY)
foo.map do |item|
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`.
^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`.
next unless item.bar?
item
end.compact
RUBY

expect_correction <<~RUBY
foo.reject { |item| item.bar? }
foo.select { |item| item.bar? }
RUBY
end

Expand Down

0 comments on commit 29c47f8

Please sign in to comment.