Sha256: c2b70f25113145da96e61d441a3fa943c0ca7c15d88aaade4b7fb8f6c1657a46

Contents?: true

Size: 609 Bytes

Versions: 1

Compression:

Stored size: 609 Bytes

Contents

require 'quick_random_records/version'
require 'active_record'
require 'rails_or'

class ActiveRecord::Base
  def self.random_records(quantity)
    id_range = 1..self.last.id
    sample_ids = [*id_range].sample(quantity)
    samples = self.where(id: sample_ids)

    while samples.size < quantity
      complement = []

      while complement.empty?
        complement_id = rand(id_range)
        next if sample_ids.include?(complement_id)

        sample_ids << complement_id
        complement = self.where(id: complement_id)
      end

      samples = samples.or(complement)
    end

    samples
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
quick_random_records-0.1.0 lib/quick_random_records.rb