Module: Mongoid::Contextual::Aggregable::Memory
| Relationships & Source Files | |
| Extension / Inclusion / Inheritance Descendants | |
|
Included In:
| |
| Super Chains via Extension / Inclusion / Inheritance | |
|
Instance Chain:
self,
::Mongoid::FieldReadable
|
|
| Defined in: | lib/mongoid/contextual/aggregable/memory.rb |
Overview
Contains behavior for aggregating values in memory.
Instance Method Summary
-
#aggregates(field) ⇒ Hash
Get all the aggregate values for the provided field.
-
#avg(field) ⇒ Numeric
Get the average value of the provided field.
-
#max(field = nil) ⇒ Numeric | Document
Get the max value of the provided field.
-
#min(field = nil) ⇒ Numeric | Document
Get the min value of the provided field.
-
#sum(field = nil) ⇒ Numeric
Get the sum value of the provided field.
-
#aggregate_by(field, method) ⇒ Numeric | nil
private
Internal use only
Aggregate by the provided field and method.
::Mongoid::FieldReadable - Included
| #read_field_value | Read the value of the given field name from the given document. |
| #readable_method_for | Resolve the given name to a method that is declared by the given class, and therefore safe to send to one of its instances. |
Instance Method Details
#aggregate_by(field, method) ⇒ Numeric | nil (private)
Aggregate by the provided field and method.
# File 'lib/mongoid/contextual/aggregable/memory.rb', line 118
def aggregate_by(field, method) return nil unless any? map { |doc| read_field_value(doc, field) }.compact.public_send(method) end
#aggregates(field) ⇒ Hash
Get all the aggregate values for the provided field.
Provided for interface consistency with Mongo.
# File 'lib/mongoid/contextual/aggregable/memory.rb', line 20
def aggregates(field) %w[count sum avg min max].each_with_object({}) do |method, hash| hash[method] = send(method, field) end end
#avg(field) ⇒ Numeric
Get the average value of the provided field.
#max(field = nil) ⇒ Numeric | Document
Get the max value of the provided field. If provided a block, will
return the ::Mongoid::Document with the greatest value for the field, in
accordance with Ruby's enumerable API.
# File 'lib/mongoid/contextual/aggregable/memory.rb', line 58
def max(field = nil) return super() if block_given? aggregate_by(field, :max) end
#min(field = nil) ⇒ Numeric | Document
Get the min value of the provided field. If provided a block, will
return the ::Mongoid::Document with the smallest value for the field, in
accordance with Ruby's enumerable API.
# File 'lib/mongoid/contextual/aggregable/memory.rb', line 80
def min(field = nil) return super() if block_given? aggregate_by(field, :min) end
#sum(field = nil) ⇒ Numeric
Get the sum value of the provided field. If provided a block, will return the sum in accordance with Ruby's enumerable API.
# File 'lib/mongoid/contextual/aggregable/memory.rb', line 99
def sum(field = nil) return super(field || 0) if block_given? aggregate_by(field, :sum) || 0 end