diff --git a/lib/mongoid/contextual/aggregable/memory.rb b/lib/mongoid/contextual/aggregable/memory.rb index 7e328fae92..ae4aacffd2 100644 --- a/lib/mongoid/contextual/aggregable/memory.rb +++ b/lib/mongoid/contextual/aggregable/memory.rb @@ -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 diff --git a/lib/mongoid/contextual/aggregable/mongo.rb b/lib/mongoid/contextual/aggregable/mongo.rb index 1b050281f5..a7972ae0a2 100644 --- a/lib/mongoid/contextual/aggregable/mongo.rb +++ b/lib/mongoid/contextual/aggregable/mongo.rb @@ -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 diff --git a/spec/mongoid/contextual/aggregable/memory_spec.rb b/spec/mongoid/contextual/aggregable/memory_spec.rb index c485044f23..804bbce8d5 100644 --- a/spec/mongoid/contextual/aggregable/memory_spec.rb +++ b/spec/mongoid/contextual/aggregable/memory_spec.rb @@ -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 diff --git a/spec/mongoid/contextual/aggregable/mongo_spec.rb b/spec/mongoid/contextual/aggregable/mongo_spec.rb index 75615da870..307b708c28 100644 --- a/spec/mongoid/contextual/aggregable/mongo_spec.rb +++ b/spec/mongoid/contextual/aggregable/mongo_spec.rb @@ -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