Skip to content

Commit

Permalink
[Fix rubocop#207] Fix an error for Performance/Sum
Browse files Browse the repository at this point in the history
Fixes rubocop#207.

This PR fixes an error for `Performance/Sum` when using
`map(&do_something).sum` without receiver.
  • Loading branch information
koic committed Jan 18, 2021
1 parent 7a29c60 commit b441ef0
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## master (unreleased)

### Bug fixes

* [#207](https://github.com/rubocop-hq/rubocop-performance/issues/207): Fix an error for `Performance/Sum` when using `map(&do_something).sum` without receiver. ([@koic][])

## 1.9.2 (2021-01-01)

### Bug fixes
Expand Down
10 changes: 8 additions & 2 deletions lib/rubocop/cop/performance/sum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,9 @@ def autocorrect_sum_map(corrector, sum, map, init)
replacement = build_good_method(init, block_pass)

corrector.remove(sum_range)
corrector.replace(map_range, ".#{replacement}")

dot = '.' if map.receiver
corrector.replace(map_range, "#{dot}#{replacement}")
end

def sum_method_range(node)
Expand Down Expand Up @@ -228,7 +230,11 @@ def build_block_bad_method(method, init, var_acc, var_elem, body)
end

def method_call_with_args_range(node)
node.receiver.source_range.end.join(node.source_range.end)
if (receiver = node.receiver)
receiver.source_range.end.join(node.source_range.end)
else
node.source_range
end
end
end
end
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/performance/sum_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,17 @@
RUBY
end

it "registers an offense and corrects when using `#{method}(&:count).sum`" do
expect_offense(<<~RUBY, method: method)
%{method}(&:count).sum
^{method}^^^^^^^^^^^^^ Use `sum { ... }` instead of `%{method} { ... }.sum`.
RUBY

expect_correction(<<~RUBY)
sum(&:count)
RUBY
end

it "registers an offense and corrects when using `array.#{method}(&:count).sum(10)`" do
expect_offense(<<~RUBY, method: method)
array.%{method}(&:count).sum(10)
Expand Down

0 comments on commit b441ef0

Please sign in to comment.