Sha256: 28d9d992ad984a6d4dacb2dc63fa117efe92ef184242c3f3092ba1f423eff34d

Contents?: true

Size: 651 Bytes

Versions: 3

Compression:

Stored size: 651 Bytes

Contents

module MongoidExt
  module Random
    extend ActiveSupport::Concern

    included do
      field :_random, :type => Float, :default => lambda{rand}
      field :_random_times, :type => Float, :default => 0.0

      index :_random
      index :_random_times
    end

    module ClassMethods
      def random(conditions = {})
        r = rand()
        doc = self.where(conditions.merge(:_random.gte => r)).order_by(:_random_times.asc, :_random.asc).first ||
              self.where(conditions.merge(:_random.lte => r)).order_by(:_random_times.asc, :_random.asc).first
        doc.inc(:_random_times, 1.0) if doc
        doc
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
mongoid_ext-0.7.1 lib/mongoid_ext/random.rb
mongoid_ext-0.6.2 lib/mongoid_ext/random.rb
mongoid_ext-0.6.1 lib/mongoid_ext/random.rb