File tree Expand file tree Collapse file tree 4 files changed +30
-4
lines changed
lib/mongoid/contextual/aggregable
spec/mongoid/contextual/aggregable Expand file tree Collapse file tree 4 files changed +30
-4
lines changed Original file line number Diff line number Diff line change @@ -90,11 +90,12 @@ def min(field = nil)
90
90
# @example Get the sum for the provided block.
91
91
# aggregable.sum(&:likes)
92
92
#
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.
94
95
#
95
96
# @return [ Numeric ] The sum value.
96
97
def sum ( field = nil )
97
- return super ( ) if block_given?
98
+ return super ( field || 0 ) if block_given?
98
99
99
100
aggregate_by ( field , :sum ) || 0
100
101
end
Original file line number Diff line number Diff line change @@ -96,11 +96,14 @@ def min(field = nil)
96
96
# @example Get the sum for the provided block.
97
97
# aggregable.sum(&:likes)
98
98
#
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.
100
101
#
101
102
# @return [ Float ] The sum value.
102
103
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
104
107
end
105
108
106
109
private
Original file line number Diff line number Diff line change 570
570
expect ( sum ) . to eq ( 1500 )
571
571
end
572
572
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
573
584
end
574
585
end
Original file line number Diff line number Diff line change 515
515
expect ( sum ) . to eq ( 1500 )
516
516
end
517
517
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
518
529
end
519
530
end
520
531
You can’t perform that action at this time.
0 commit comments