Ruby on Rails
RandomSample

A ruby based approach to selecting random records(as explained in HowtoSelectRandomRecords). This approach extends ActiveRecord with a random_sample method.

Installation

  1. Place this code in your /lib directory
  2. /lib/random_sample.rb
    #
  3. RandomSample adds a #random_sample method to AR objects
  4. thanks to bitsweat for the examples

module Enumerable
def random_sample(n)
sort_by { rand }.slice(0, n)
end
end

module RandomSample
def self.append_features(base)
def base.random_sample(n = 1)
r = find(find_by_sql(“select #{primary_key} from #{table_name}”).random_sample(n).map { |q| q.id })
end
end
end

  1. Include the module into \ActiveRecord by adding the following at the bottom of your \config\environment.rb file:
    
    class ActiveRecord::Base
        include RandomSample
    end
    

Use

RandomSample adds a single method random_sample to all \ActiveRecord objects. random_sample will return an array of records, or nil if none were found.

Examples


irb(main):001:0> Keyword.random_sample(3)
=> [#<Keyword:0x3bde0b8 @attributes={"word"=>"tall", "id"=>"1", "genre"=>nil}>, #<Keyword:0x3bde040 @attributes={"word"=
>"dancer", "id"=>"4", "genre"=>nil}>, #<Keyword:0x3bddf68 @attributes={"word"=>"masked", "id"=>"5", "genre"=>nil}>]
irb(main):002:0> Keyword.random_sample(1).first.word
=> "tights"
irb(main):003:0> Keyword.random_sample(1).first.word
=> "superhero"

category: Example

Note: At least on my setup, this returns a random sample, but sorted (ascending ID by default)
Since I needed random order as well, I modified it slightly:


module RandomSample
    def self.append_features(base)
        def base.random_sample(n = 1)
            r = find(find_by_sql("select #{primary_key} from #{table_name}").random_sample(n).map { |q| q.id })
            # added another sort to ensure random ordering
            r = r.sort_by { rand }
        end
    end
end

Question

How can we modify this code to make the random a litte less random. I would like for example to be able to have a different random each weeks… so the random should care about the Time… i ve tried to replace the “rand” by somehing like Time.now etc… but nothing worked at all… any idea ?

thanks a lot