I want an enum of sorts in my Rails application.
I have a Project object, which has four possible status settings, as
indicated here:
class Project < ActiveRecord:Base
…
class << self
def statuses
[ ‘Hidden’, ‘Available’, ‘In progress’, ‘Complete’ ]
end
end
…
end
These are not expected to change, so hardcoding is preferable. Of
course, there is a ‘status’ column in the project table, so rails
creates a ‘status’ accessor.
However, later in the code I will want to check the status myself. For
example, ‘Complete’ projects won’t be shown in the same place as
‘Available’ ones, and ‘In progress’ and ‘Hidden’ projects won’t be shown
at all (not sure about In progress ATM though, so I want to keep it
flexible). Now, it would be pretty ugly checking
if a_project.status == 2 # Project is in progress
So one possibility is to add methods like
class Project
def in_progress?
self.status == 2
end
end
Another interesting option is this:
class Project
def status_is?(_status)
[ :hidden, :available, :in_progress, :complete ][self.status] ==
_status
end
end
If only I could count on hashes staying in order, a very pretty solution
would
be:
class Project
class << self
def statuses
{ :hidden => ‘Hidden’, :available => ‘Available’,
:in_progress => ‘In progress’, :complete => ‘Complete’ }
# Use Project.statuses.values for the dropdown
end
end
def status_is?(_status)
Project.statuses.keys[self.status] == _status
end
end
Unfortunately, “The order in which you traverse a hash by either key or
value may seem arbitrary, and will generally not be in the insertion
order.” (ri).
Any other ideas for elegance?