Created
January 21, 2011 22:07
-
-
Save outoftime/790523 to your computer and use it in GitHub Desktop.
Instantiate the results of map-reduce operations as Mongoid documents
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Mongoid | |
class Criteria | |
include Criterion::MapReduce | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Mongoid | |
module Criterion | |
module MapReduce | |
def map_reduce(map, reduce) | |
options = self.options.dup | |
options.merge!(:query => selector) if selector.present? | |
klass.collection.map_reduce(map, reduce, options) | |
end | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Mongoid | |
module MapReduceDocument | |
extend ActiveSupport::Concern | |
include Document #XXX Ideally we'd have a read-only document here. | |
included do | |
private_class_method :new | |
Mongoid::Persistence.instance_methods.each do |method| | |
undef_method method | |
end | |
end | |
module ClassMethods | |
def run(scope) | |
collection = scope.all.map_reduce(@map, @reduce) | |
clazz = Class.new(self) | |
clazz.collection_name = collection.name | |
clazz._collection = Mongoid::Collection.new(clazz, collection.name) | |
clazz.create_indexes | |
clazz.all | |
end | |
def instantiate(attrs) | |
super(attrs['value'].merge('_id' => attrs['_id'])) | |
end | |
def map(map) | |
@map = map | |
end | |
def reduce(reduce) | |
@reduce = reduce | |
end | |
def hereditary? | |
!!(MapReduceDocument > superclass.superclass) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment