Instead of Rails :unique finder, Array#singular
There was recently some talk about a suggested :unique finder for rails.
Although this seems like overkill, I occasionally do things like array.size == 1 && array.first, which is basically all the :unique finder would do.
Without further ado, here’s a five-line monkeypatch to Array that lets you get the singular item from an array (or blow up if you expect one and there isn’t):
class Array def singular?() size == 1 end def singular() singular?? first : nil end def singular!() singular or raise "not singular" end end
Now you can simulate the :unique finder just by doing
my_singular_wibble = Widget.wibbles.first.singular.
This, along with lots of other fun monkeypatches, is now in freighthopper, my collection of extensions and monkeypatches.