Created
November 18, 2015 16:36
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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