Skip to content

Commit

Permalink
Merge pull request #208 from koic/fix_an_error_for_performance_sum
Browse files Browse the repository at this point in the history
[Fix #207] Fix an error for `Performance/Sum`
  • Loading branch information
koic committed Jan 22, 2021
2 parents 209a88b + 750b396 commit 13950c8
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 @@ -6,6 +6,10 @@

* [#190](https://github.com/rubocop-hq/rubocop-performance/pull/190): Add new `Performance/RedundantSplitRegexpArgument` cop. ([@mfbmina][])

### 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][])

### Changes

* [#205](https://github.com/rubocop-hq/rubocop-performance/issues/205): Update `Performance/ConstantRegexp` to allow memoized regexps. ([@dvandersluis][])
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 13950c8

Please sign in to comment.