Skip to content

Instantly share code, notes, and snippets.

@xixilive
Created July 3, 2012 03:27
Show Gist options
  • Save xixilive/3037403 to your computer and use it in GitHub Desktop.
Save xixilive/3037403 to your computer and use it in GitHub Desktop.
RandomSelector for ActiveModel via Mongoid
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