Created
July 3, 2012 03:27
-
-
Save xixilive/3037403 to your computer and use it in GitHub Desktop.
RandomSelector for ActiveModel via Mongoid
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 RandomSelector | |
class << self | |
def included(base) | |
base.module_eval do | |
def self.random n, conditions=nil | |
criteria = conditions.is_a?(Mongoid::Criteria) ? (self.where({}).merge(conditions)) : self.where(conditions||{}) | |
cc = criteria.count | |
mo = [cc-n,2].max | |
criteria.skip((rand*cc%mo).to_i).limit(n) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment