Skip to content

Instantly share code, notes, and snippets.

@dblock
Created July 15, 2012 00:11
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 dblock/3113975 to your computer and use it in GitHub Desktop.
Save dblock/3113975 to your computer and use it in GitHub Desktop.
Returning a sample set from a Mongoid collection.
module Mongoid
class Criteria
def sample(n = 1)
indexes = (0..self.count-1).sort_by{ rand }.slice(0,n).collect!
if n == 1
return self.skip(indexes.first).first
else
return indexes.map{ |index| self.skip(index).first }
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment