From: Logan Capaldo Date: 2006-09-05T21:49:33+09:00 Subject: Re: Enum On Sep 5, 2006, at 5:24 AM, Ohad Lutzky wrote: > 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 > > [snip] > Any other ideas for elegance? > I usually do: class A [ 'Hidden', 'Available', 'Etc' ].each do |s| const_set(s, k = Object.new) def k.to_s "A::#{s}" end k.freeze end end Then you can say if obj.status == A::Available, etc. > > -- > Posted via http://www.ruby-forum.com/. >