Skip to content

Commit

Permalink
Merge pull request #264 from mvz/fix-sum-cop
Browse files Browse the repository at this point in the history
Fix error in Performance/Sum when method has no brackets
  • Loading branch information
koic committed Oct 16, 2021
2 parents 05bae09 + b59c260 commit ccc9afe
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -296,3 +296,4 @@
[@dvandersluis]: https://github.com/dvandersluis
[@ghiculescu]: https://github.com/ghiculescu
[@mfbmina]: https://github.com/mfbmina
[@mvz]: https://github.com/mvz
1 change: 1 addition & 0 deletions changelog/fix_fix_error_in_performancesum_when_method.md
@@ -0,0 +1 @@
* [#264](https://github.com/rubocop/rubocop-performance/pull/264): Fix error in Performance/Sum when method has no brackets. ([@mvz][])
2 changes: 1 addition & 1 deletion lib/rubocop/cop/performance/sum.rb
Expand Up @@ -156,7 +156,7 @@ def autocorrect_sum_map(corrector, sum, map, init)
end

def sum_method_range(node)
range_between(node.loc.selector.begin_pos, node.loc.end.end_pos)
range_between(node.loc.selector.begin_pos, node.loc.expression.end_pos)
end

def sum_map_range(map, sum)
Expand Down
31 changes: 31 additions & 0 deletions spec/rubocop/cop/performance/sum_spec.rb
Expand Up @@ -46,6 +46,17 @@
RUBY
end

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

expect_correction(<<~RUBY)
array.sum
RUBY
end

it "registers an offense and corrects when using `array.#{method}(0.0, :+)`" do
expect_offense(<<~RUBY, method: method)
array.#{method}(0.0, :+)
Expand Down Expand Up @@ -88,6 +99,15 @@

expect_no_corrections
end

it 'does not autocorrect `:+` without brackets when initial value is not provided' do
expect_offense(<<~RUBY, method: method)
array.#{method} :+
^{method}^^^ Use `sum` instead of `#{method}(:+)`, unless calling `#{method}(:+)` on an empty array.
RUBY

expect_no_corrections
end
end

context 'when `SafeAutoCorrect: false' do
Expand All @@ -114,6 +134,17 @@
array.sum
RUBY
end

it 'autocorrects `:+` without brackets when initial value is not provided' do
expect_offense(<<~RUBY, method: method)
array.#{method} :+
^{method}^^^ Use `sum` instead of `#{method}(:+)`, unless calling `#{method}(:+)` on an empty array.
RUBY

expect_correction(<<~RUBY)
array.sum
RUBY
end
end

it "registers an offense and corrects when using `array.#{method}(0, &:+)`" do
Expand Down

0 comments on commit ccc9afe

Please sign in to comment.