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 b29ba24
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 8 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][])
7 changes: 5 additions & 2 deletions lib/rubocop/cop/style/map_compact_with_conditional_block.rb
Expand Up @@ -115,11 +115,14 @@ def truthy_branch_for_if?(node)

def truthy_branch_for_guard?(node)
if_node = node.left_sibling
if_branch = if_node.if_branch

return false unless if_branch.next_type?

if if_node.if? || if_node.ternary?
if_node.else_branch.nil?
if_branch.arguments.any? && if_node.else_branch.nil?
elsif if_node.unless?
if_node.if_branch.nil?
if_branch.arguments.none? && if_node.else_branch.nil?
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 b29ba24

Please sign in to comment.