A ruby based approach to selecting random records(as explained in HowtoSelectRandomRecords). This approach extends ActiveRecord with a @random_sample@ method.


h2. Installation

# Place this code in your @/lib@ directory <pre><code>
# /lib/random_sample.rb
#
# RandomSample adds a #random_sample method to AR objects
# 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
</code></pre>

# Include the module into \ActiveRecord by adding the following at the bottom of your @\config\environment.rb@ file:<pre><code>
class ActiveRecord::Base
    include RandomSample
end
</code></pre>

h2. 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.

h4. Examples

<pre><code>
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"
</code></pre>

category: Example
