Skip to content

Instantly share code, notes, and snippets.

@Supernats
Created August 1, 2014 04:34
Show Gist options
  • Select an option

  • Save Supernats/285b20c3ca998ae701be to your computer and use it in GitHub Desktop.

Select an option

Save Supernats/285b20c3ca998ae701be to your computer and use it in GitHub Desktop.
class ActiveRecord::Base
def self.sample(n = 1)
case n <=> 1
when -1
puts "don't be a shit"
nil
when 0
chosen_rand = rand(self.count) + 1
self.find(chosen_rand)
when 1
record_count = self.count
records = Set.new
until records.count == n
chosen_rand = rand(record_count) + 1
user = self.find(chosen_rand)
records.add(user) unless records.include?(user)
end
records
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment