Sha256: 13daf4771bdc09ec5869e77a7408368d5d4fa0a26ee374e1324c9c72931fa7a9

Contents?: true

Size: 668 Bytes

Versions: 1

Compression:

Stored size: 668 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 => 1})
      index({:_random_times => 1})
    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

1 entries across 1 versions & 1 rubygems

Version Path
mongoid_ext-0.9.0 lib/mongoid_ext/random.rb