Class: Mongoid::MapReduce::Reducer
- Inherits:
-
Object
- Object
- Mongoid::MapReduce::Reducer
- Defined in:
- lib/mongoid/mapreduce/reducer.rb
Instance Attribute Summary collapse
-
#count_field ⇒ Object
Returns the value of attribute count_field.
Instance Method Summary collapse
-
#field(sym, options = {}) ⇒ Object
Adds a field to the map/reduce operation.
-
#formula ⇒ Object
Expose the currently selected formula, from instance variable if possible.
-
#initialize(klass, selector, options) ⇒ Reducer
constructor
Initialize the reducer with given values.
-
#run ⇒ Object
Runs the map/reduce operation and returns the result.
Constructor Details
#initialize(klass, selector, options) ⇒ Reducer
Initialize the reducer with given values
klass - Mongoid model Class selector - Selector to use for search (often from criteria) options - Hash of options:
count_field - Name of field used to store count in results
formula - Name of formula to be used (underscore)
map_key - Name of field used as key in map function
Returns nothing
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/mongoid/mapreduce/reducer.rb', line 21 def initialize(klass, selector, ) [:klass] = klass [:selector] = selector [:formula] ||= :aggregate_fields @klass = klass @selector = selector @formula_name = [:formula] @options = @fields = {} if .key?(:fields) [:fields].each do |f| field f.to_sym end end end |
Instance Attribute Details
#count_field ⇒ Object
Returns the value of attribute count_field.
9 10 11 |
# File 'lib/mongoid/mapreduce/reducer.rb', line 9 def count_field @count_field end |
Instance Method Details
#field(sym, options = {}) ⇒ Object
Adds a field to the map/reduce operation
sym - String or Symbol, name of field to add
Returns nothing.
57 58 59 60 |
# File 'lib/mongoid/mapreduce/reducer.rb', line 57 def field(sym, ={}) [:type] ||= Integer @fields[sym.to_sym] = end |
#formula ⇒ Object
Expose the currently selected formula, from instance variable if possible.
Returns Formula object.
42 43 44 45 46 47 48 49 50 |
# File 'lib/mongoid/mapreduce/reducer.rb', line 42 def formula # Find and initialize our formula klass = "Mongoid::MapReduce::Formula::#{@formula_name.to_s.camelize}" begin @formula ||= klass.constantize.new(@fields, @options) rescue NameError raise "Could not load formula for #{klass}" end end |
#run ⇒ Object
Runs the map/reduce operation and returns the result
Returns Mongoid::MapReduce::Results object (array) containing Mongoid::MapReduce::Document objects (hashes)
66 67 68 69 70 71 72 73 74 |
# File 'lib/mongoid/mapreduce/reducer.rb', line 66 def run begin coll = @klass.collection.map_reduce(formula.map, formula.reduce, { query: @selector, out: "#map_reduce" } ).find.to_a rescue raise "Error: could not execute map reduce function" end formula.process(coll) end |