Skip to content

Commit

Permalink
Add special handling on negating begin node
Browse files Browse the repository at this point in the history
  • Loading branch information
r7kamura committed Oct 5, 2022
1 parent 81cd676 commit 65e43ed
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
8 changes: 7 additions & 1 deletion lib/rubocop/cop/performance/count.rb
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,13 @@ def negate_block_pass_reject(corrector, node)
end

def negate_block_reject(corrector, node)
corrector.replace(node.receiver.body, negate_expression(node.receiver.body))
target =
if node.receiver.body.begin_type?
node.receiver.body.children.last
else
node.receiver.body
end
corrector.replace(target, negate_expression(target))
end

def negate_expression(node)
Expand Down
31 changes: 29 additions & 2 deletions spec/rubocop/cop/performance/count_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -306,8 +306,35 @@ def count(&block)

expect_correction(<<~RUBY)
array.count {
!(foo
bar)
foo
!(bar)
}
RUBY
end
end

context 'with `reject` with some conditional statement and `length`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
array.reject {
^^^^^^^^ Use `count` instead of `reject...length`.
foo
if bar
baz
else
qux
end
}.length
RUBY

expect_correction(<<~RUBY)
array.count {
foo
!(if bar
baz
else
qux
end)
}
RUBY
end
Expand Down

0 comments on commit 65e43ed

Please sign in to comment.