Skip to content

Commit

Permalink
MONGOID-5786: Fix some compatibility issues with Enumerable API (#5831)
Browse files Browse the repository at this point in the history
* Fix compatibility with Enumerable#sum API

* Update documentation for the sum() method

* Update documentation for sum() method

---------

Co-authored-by: Jamis Buck <[email protected]>
  • Loading branch information
cperezabo and jamis authored Jun 17, 2024
1 parent 1f1f1e7 commit 08547c3
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 4 deletions.
5 changes: 3 additions & 2 deletions lib/mongoid/contextual/aggregable/memory.rb
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,12 @@ def min(field = nil)
# @example Get the sum for the provided block.
# aggregable.sum(&:likes)
#
# @param [ Symbol ] field The field to sum.
# @param [ Symbol | Numeric ] field The field to sum, or the intial
# value of the sum when a block is given.
#
# @return [ Numeric ] The sum value.
def sum(field = nil)
return super() if block_given?
return super(field || 0) if block_given?

aggregate_by(field, :sum) || 0
end
Expand Down
7 changes: 5 additions & 2 deletions lib/mongoid/contextual/aggregable/mongo.rb
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,14 @@ def min(field = nil)
# @example Get the sum for the provided block.
# aggregable.sum(&:likes)
#
# @param [ Symbol ] field The field to sum.
# @param [ Symbol | Numeric ] field The field to sum, or the initial
# value of the sum when a block is given.
#
# @return [ Float ] The sum value.
def sum(field = nil)
block_given? ? super() : aggregates(field)["sum"] || 0
return super(field || 0) if block_given?

aggregates(field)["sum"] || 0
end

private
Expand Down
11 changes: 11 additions & 0 deletions spec/mongoid/contextual/aggregable/memory_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -570,5 +570,16 @@
expect(sum).to eq(1500)
end
end

context "when provided a block with initial value" do

let(:sum) do
context.sum(500, &:likes)
end

it "returns the sum for the provided block starting from initial value" do
expect(sum).to eq(2000)
end
end
end
end
11 changes: 11 additions & 0 deletions spec/mongoid/contextual/aggregable/mongo_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,17 @@
expect(sum).to eq(1500)
end
end

context "when provided a block with initial value" do

let(:sum) do
context.sum(500, &:likes)
end

it "returns the sum for the provided block starting from initial value" do
expect(sum).to eq(2000)
end
end
end
end

Expand Down

0 comments on commit 08547c3

Please sign in to comment.