Skip to content

Commit

Permalink
Fix error in Performance/Sum when method has no brackets
Browse files Browse the repository at this point in the history
This fixes an issue where code like the following would cause an error
in the Performance/Sum cop:

  arr.inject :+
  • Loading branch information
mvz committed Oct 16, 2021
1 parent 05bae09 commit 14bd0be
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#264](https://github.com/rubocop/rubocop/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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 14bd0be

Please sign in to comment.