Skip to content

Commit 08547c3

Browse files
cperezabojamis
andauthored
MONGOID-5786: Fix some compatibility issues with Enumerable API (#5831)
* Fix compatibility with Enumerable#sum API * Update documentation for the sum() method * Update documentation for sum() method --------- Co-authored-by: Jamis Buck <[email protected]>
1 parent 1f1f1e7 commit 08547c3

File tree

4 files changed

+30
-4
lines changed

4 files changed

+30
-4
lines changed

lib/mongoid/contextual/aggregable/memory.rb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,11 +90,12 @@ def min(field = nil)
9090
# @example Get the sum for the provided block.
9191
# aggregable.sum(&:likes)
9292
#
93-
# @param [ Symbol ] field The field to sum.
93+
# @param [ Symbol | Numeric ] field The field to sum, or the intial
94+
# value of the sum when a block is given.
9495
#
9596
# @return [ Numeric ] The sum value.
9697
def sum(field = nil)
97-
return super() if block_given?
98+
return super(field || 0) if block_given?
9899

99100
aggregate_by(field, :sum) || 0
100101
end

lib/mongoid/contextual/aggregable/mongo.rb

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,11 +96,14 @@ def min(field = nil)
9696
# @example Get the sum for the provided block.
9797
# aggregable.sum(&:likes)
9898
#
99-
# @param [ Symbol ] field The field to sum.
99+
# @param [ Symbol | Numeric ] field The field to sum, or the initial
100+
# value of the sum when a block is given.
100101
#
101102
# @return [ Float ] The sum value.
102103
def sum(field = nil)
103-
block_given? ? super() : aggregates(field)["sum"] || 0
104+
return super(field || 0) if block_given?
105+
106+
aggregates(field)["sum"] || 0
104107
end
105108

106109
private

spec/mongoid/contextual/aggregable/memory_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -570,5 +570,16 @@
570570
expect(sum).to eq(1500)
571571
end
572572
end
573+
574+
context "when provided a block with initial value" do
575+
576+
let(:sum) do
577+
context.sum(500, &:likes)
578+
end
579+
580+
it "returns the sum for the provided block starting from initial value" do
581+
expect(sum).to eq(2000)
582+
end
583+
end
573584
end
574585
end

spec/mongoid/contextual/aggregable/mongo_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -515,6 +515,17 @@
515515
expect(sum).to eq(1500)
516516
end
517517
end
518+
519+
context "when provided a block with initial value" do
520+
521+
let(:sum) do
522+
context.sum(500, &:likes)
523+
end
524+
525+
it "returns the sum for the provided block starting from initial value" do
526+
expect(sum).to eq(2000)
527+
end
528+
end
518529
end
519530
end
520531

0 commit comments

Comments
 (0)