Module: Mongoid::Random::ClassMethods

Defined in:
lib/mongoid/random.rb

Instance Method Summary collapse

Instance Method Details

#random(count = 1, random_key = rand) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/mongoid/random.rb', line 14

def random(count=1, random_key=rand)
  if where(:_randomization_key => { '$gte' => random_key }).count >= count
    where(:_randomization_key => { '$gte' => random_key })
  elsif where(:_randomization_key => { '$lte' => random_key }).count >= count
    where(:_randomization_key => { '$lte' => random_key })
  else
    where(:_randomization_key.ne => nil)
  end.order_by([ [ [ :_id, :_randomization_key ].sample, [ :asc, :desc ].sample ] ]).limit(count)
end