Class: Mongoid::Contextual::Aggregable::Aggregates

Inherits:
Object
  • Object
show all
Defined in:
lib/mongoid/contextual/aggregable/aggregates.rb

Overview

Contains behaviour for aggregating values in Mongo.

Instance Method Summary collapse

Constructor Details

#initialize(context) ⇒ Aggregates

Returns a new instance of Aggregates.



14
15
16
17
# File 'lib/mongoid/contextual/aggregable/aggregates.rb', line 14

def initialize(context)
  @context = context
  @commands = []
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object (protected)



72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/mongoid/contextual/aggregable/aggregates.rb', line 72

def method_missing(name, *args, &block)
  if @context.scopes.has_key?(name)
    criteria = @context.scopes[name][:scope].call(*args)
    @commands.push(to_match(criteria))
  elsif @context.respond_to?(name)
    criteria = @context.send(name, *args)
    @commands.push(to_match(criteria))
  else
    raise Errors::UnknownAttribute.new(@context, name)
  end
  self
end

Instance Method Details

#allObject



19
20
21
# File 'lib/mongoid/contextual/aggregable/aggregates.rb', line 19

def all
  @context.collection.aggregate(@commands)
end

#compute(field) ⇒ Object



58
59
60
61
62
63
64
# File 'lib/mongoid/contextual/aggregable/aggregates.rb', line 58

def compute(field)
  res = all.inject(Hash.new 0) {
      |compute, item| compute[:count] += 1; compute[:sum] += item["#{field}"] unless item["#{field}"].nil?; compute
  }
  res[:avg] = res[:sum] / (res[:count] != 0 ? res[:count] : 1 )
  res
end

#countObject



66
67
68
# File 'lib/mongoid/contextual/aggregable/aggregates.rb', line 66

def count
  all.count
end

#explainObject



48
49
50
# File 'lib/mongoid/contextual/aggregable/aggregates.rb', line 48

def explain
  @commands.to_json
end

#group(key, *args) ⇒ Object



23
24
25
26
# File 'lib/mongoid/contextual/aggregable/aggregates.rb', line 23

def group(key, *args)
  @commands.push(Commands::Group.new(key, *args))
  self
end

#limit(*args) ⇒ Object



43
44
45
46
# File 'lib/mongoid/contextual/aggregable/aggregates.rb', line 43

def limit(*args)
  @commands.push(Commands::Limit.new(*args))
  self
end

#or(*args) ⇒ Object



38
39
40
41
# File 'lib/mongoid/contextual/aggregable/aggregates.rb', line 38

def or(*args)
  @commands.push(Commands::Or.new(*args))
  self
end

#project(*args) ⇒ Object



28
29
30
31
# File 'lib/mongoid/contextual/aggregable/aggregates.rb', line 28

def project(*args)
  @commands.push(Commands::Project.new(*args))
  self
end

#sort(*args) ⇒ Object



33
34
35
36
# File 'lib/mongoid/contextual/aggregable/aggregates.rb', line 33

def sort(*args)
  @commands.push(Commands::Sort.new(*args))
  self
end

#sum(field) ⇒ Object



52
53
54
55
56
# File 'lib/mongoid/contextual/aggregable/aggregates.rb', line 52

def sum(field)
  all.inject(0) {
      |sum, item| sum + (item[field.to_s] || 0)
  }
end