There are plenty of times when I want to grab either one or many random records from a database in Rails. For instance, one random user, one random post, 5 random items, etc. Honestly, it’s one of those things I do in nearly every app I’ve written, so a while ago I created a module to add to any ActiveRecord class that gave me one() and some() methods. This way, I can just include Randomizer and have the methods. Everyone probably already has their method– I actually got this from somewhere else and modified it a bit– I figured I’d post mine in case someones searching the innerwebs.1
[gist id=450723]
- It’s one of those things that could be in a plugin or gem, but I’m getting really sick of gems and plugins that carry all the infrastructure to support being gems or plugins when they are really simply a wee bit of code in one small file. Thus, I’m starting to just publish Gists and add them manually to my lib directory. They’re not really gems– they’re more like ungems. Maybe shards. [↩]


