I'm launching a course about Next.js + React.jsLearn more

Nifty enums for Rails apps

2012-04-22 · 1 min read

Yesterday, when wondering about the best representation for enum, I came along a nifty gem called symbolize. The gem introduces an easy way to use symbols for values of an attribute. It provides a dedicated method (symbolize) that allows to return a symbol as a value of an attribute that method is used for.

It can be done like so

Two options I found pretty cool are scope and methods.

Option scope (class)

ActiveRecord flavour

FooBar.great # => FooBar.all(conditions: { quux: :great })

Mongoid flavour

FooBar.great # => FooBar.where({ quux: :great })

Scopes can be also chained.


Option methods (object)

It add fancy boolean methods to objects with enum.

  • @foobar.car?

So, wanna have cool enum inside your Rails app ? Check it on GitHub.

My Tech Newsletter

Get emails from me about programming & web development. I usually send it once a month