Sambhav Sharma Sambhav Sharma - 1 year ago 151
Ruby Question

Enums in rails: uppercase or lowercase?

With most mentions of JAVA enums on the internet, it is everywhere mentioned that enums should be all uppercase (ex: 'ACTIVE').

Like here: Coding Conventions - Naming Enums

But when it comes to RAILS, in all there examples and docs they use lowercase enum value (ex: 'active'), like here:

which makes sense since rails also provides instance methods by the name of these enums (eg: Is this the only reason why enums in RAILS are used as lowercase, or is there more to it?
Also we differ from the convention when we use enums as lowercase, should this be the case? or shall we use uppercase enums in RAILS as well?

So for example I have a status enum in my model, which can either be active, draft or inactive as per convention, should it be

enum status: {active: 1, draft: 2, inactive: 3}


enum status: {ACTIVE: 1, DRAFT: 2, INACTIVE: 3}

Which one and why?

max max
Answer Source

In Rails enums should be snake_case.

Why? Because enums are used to construct method names. And method names in Ruby should be snake_case according to the community convention. Using ALLCAPS or CamelCase can lead to bugs and confusion as the Ruby treats such identifiers as constants.

ActiveRecord::Enum is not comparable to a language level enumeration construct such as in Java.

Declare an enum attribute where the values map to integers in the database, but can be queried by name.

The keys mappings in an ActiveRecord::Enum are not constants. Rather it's just a list which is used with Ruby style metaprogramming that adds methods to make bitmask columns easier (and more fun) to work with.

In your example its actually comparable to:

enum status: [ :ACTIVE, :DRAFT, :INACTIVE ] 

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

Enums in Java are basically glorified switch statements where the class constants denote the possible values.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download