Using Enums in Rails

A principle that has guided my transition from .NET/C# to Ruby on Rails is to do things differently, “The Rails Way.” But I like enums from the old days and want to use them in Rails, darn it. This post describes how I’m structuring enums in Rails with examples of using them in my application.

The Enum Class

Rather than use symbols, frozen hash constants or a lot of fancy logic I created a straight-up class which looks much like a typical Enum Class in C#.

Before getting any further, a bit of context on the enum’s function might come in handy.  In our Rails app we have a Micropost Model serving as a shared content stream. We want to differentiate Microposts by type, the three content types as reflected in our Enum are 1) a Welcome Message from Edgar (you’ll meet Edgar later), 2) a Checkout message (again, later on Checkout), and 3) a post created by a member.

Using the Enum to Retrieve Microposts By Type

In our Micropost Model we’re adding a simple definition to which we’ll be passing the MicropostType enum. First the DEF in the Model followed by an example of it being used in Rails Console.

Passing the Enum in an HTML Form

Here we’re creating a Micropost of type MemberPost and passing the enum value in a hidden field. (3rd line from the bottom.)

Using the Enum in Creating a Micropost

Here we’re using the enum in a sessions_helper module to build and save a Micropost of an Edgar Welcome Message type.

Syntax and Filename

Notice the syntax we’re using for the enum, as we’re actually building a Class::Constant construct, but without Ruby’s convention of placing the constant in ALL CAPS.

The enum filename must conform to ruby conventions, so our MicropostType enum class filename is “micropost_type.rb.” Where to place these types of classes is a personal preference, but I like adding a project-specific folder under /lib.

Adding the Enum to the Application Path

This is more of a sidebar, but you might need to know how to add your enums folder to the application path so we don’t have to use “require” or “include” statements whenever we want to use our enum.  To do that we will add the path in /config/application.rb. In Rails 3.2.13 it looks like this.