Skip to content

Instantly share code, notes, and snippets.

@gurix
Created November 18, 2015 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gurix/50feb1bb6146d4eb922b to your computer and use it in GitHub Desktop.
Save gurix/50feb1bb6146d4eb922b to your computer and use it in GitHub Desktop.
Concern to get random document(s) from a model via mongoid, see http://stackoverflow.com/questions/7759250/mongoid-random-document/33784640#33784640
module Randomizable
extend ActiveSupport::Concern
module ClassMethods
def random(n = 1)
indexes = (0..count - 1).sort_by { rand }.slice(0, n).collect!
return skip(indexes.first).first if n == 1
indexes.map { |index| skip(index).first }
end
end
end
require 'spec_helper'
class RandomizableCollection
include Mongoid::Document
include Randomizable
field :name
end
describe RandomizableCollection do
before do
RandomizableCollection.create name: 'Hans Bratwurst'
RandomizableCollection.create name: 'Werner Salami'
RandomizableCollection.create name: 'Susi Wienerli'
end
it 'returns a random document' do
srand(2)
expect(RandomizableCollection.random(1).name).to eq 'Werner Salami'
end
it 'returns an array of random documents' do
srand(1)
expect(RandomizableCollection.random(2).map(&:name)).to eq ['Susi Wienerli', 'Hans Bratwurst']
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment