Skip to content

Instantly share code, notes, and snippets.

@outoftime
Created January 21, 2011 22:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save outoftime/790523 to your computer and use it in GitHub Desktop.
Save outoftime/790523 to your computer and use it in GitHub Desktop.
Instantiate the results of map-reduce operations as Mongoid documents
module Mongoid
class Criteria
include Criterion::MapReduce
end
end
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
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