Topic: Handling distinct values (enums)

Hey all,

How does Ruby and/or Rails handle enum like values? I'm finding myself creating a lot of constants in my Models and then creating arrays from those constants in order to get what would be the same functionality as enums provide in other classes (such as C#). It's a lot of work for such a simple thing, so it seems like there should be a better way.

For example, my Message model (for internal email-type messages within the system) looks something like this

class Message < ActiveRecord::Base
    NEW = 0
    UNREAD = 1
    READ = 2
    REPLIED = 3
    NEW_S = 'New'
    UNREAD_S = 'Unread'
    READ_S = 'Read'
    REPLIED_S = 'Replied'
    # ...

Then I use any one of those 10 values depending on my current need. Fortunately stuff like this is legal (no real surprise)

m = Message
some_variable = m::UNREAD
# etc

But all in all it seems like there's got to be a better approach. I've noticed the Ruby language has no official support for enums.

Last edited by tortoise (2006-12-18 16:26:37)

Re: Handling distinct values (enums)

Well, the Ruby way to do this would involve the tiniest bit more memory but would drastically cut down on maintenance.

class Message < ActiveRecord::Base
  Statuses = [:new, :unread, :read, :replied] # or 'Stati'
  def self.status_words
    Statuses.collect {|status| status.to_s.camelcase }

  def self.status_nums
    Statuses.collect {|array_key, value| array_key }