Skip to content

Instantly share code, notes, and snippets.

@hypomodern
Created June 19, 2012 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hypomodern/2954776 to your computer and use it in GitHub Desktop.
Save hypomodern/2954776 to your computer and use it in GitHub Desktop.
MongoMapper::Randomizer plugin
module MongoMapper
# From https://gist.github.com/901929
module Randomizer
extend ActiveSupport::Concern
included do
key :randomizer, Integer
before_create Proc.new { |doc| doc.randomizer = self.class.count }
end
module ClassMethods
# Finds non-sequential random documents.
# When using the :selector option, ensure you're hitting an index that includes :random as the last listed key.
# Additionally, do not use range queries in the selector: {http://bit.ly/gHxnLN MongoDB Indexing Advice}.
#
# @param [Hash] :limit => the number of documents to find, :selector => randomly select documents matching the criteria
# @return [Array] the randomly selected documents
def random(*args)
opts = { :limit => 1, :selector => { } }.update(args.extract_options!)
[].tap do |results|
opts[:limit].times do
number = rand(self.count)
result = where(opts[:selector]).first(:randomizer => { :$gte => number }) ||
where(opts[:selector]).first(:randomizer => { :$lte => number })
results << result if result
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment