I had to figure out Ruby on Rails enumerations and fixtures today.
The solution will be here in just a moment, but first, some gratuitous background: I was working on a Person resource — or a “Contact” resource if you prefer your people to have a CRM flare to them. Naturally, hanging off of these People (or Contacts) are as many phone numbers as they might have.
Twenty-first century people have a lot of phones.
Once you start having contacts who own lots of phones, naturally you want to know if you’re bugging someone to buy your widgets on their cell phone or their home phone or what have you.
You don’t want to store whole strings to do this, so probably you end up with a line in your schema that looks something like this:
Well, that’s fine, but in your code you don’t want to be saying “p.phone_type = 2”, because that’s not all that readable.
Now Ruby doesn’t have enums (BAD language — just for that you’re going straight to bed with no strong typing, young man). It does, however, have constants, and this Rails tip shows you how to use them.
Like me you may have opted for the simple “first approach” of adding the constants to your model, like so.
<pre class= "theme:dark-terminal lang:default decode:true " ><pre class="theme:terminal lang:default decode:true " >&lt;pre class="theme:terminal lang:ruby decode:true " &gt;class Phone &amp;lt; ActiveRecord::Base
# Type constants
HOME = 1
WORK = 2
CELL = 3
# ... more model code ...