Idiomatic way to do a non-database Enumeration?

I have a class which stores as one of its attributes a day of the week
as an integer (0-6, 0=Sunday, standard UNIXy values). I want,
obviously, the views to show the weekday name and the forms to provide
a drop-down with the weekday names. Essentially it’s a vrtual
attribute whose value is the localized weekday name, which maps to the
integer value that’s actually stored.

There are a lot of approaches, but I was wondering what the idiomatic
Rails-y way of doing it is. Should I create a Weekday class? It
wouldn’t be backed by the db - that’s not localizable or DRY…

Any help appreciated.

On Thu, Aug 23, 2007 at 07:38:27PM -0000, Zeekar wrote:

I have a class which stores as one of its attributes a day of the week
as an integer (0-6, 0=Sunday, standard UNIXy values). I want,
obviously, the views to show the weekday name and the forms to provide
a drop-down with the weekday names. Essentially it’s a vrtual
attribute whose value is the localized weekday name, which maps to the
integer value that’s actually stored.

There are two pieces to this. One is how you deal with the data readably
in
your code, the other is rendering a localized version.

There are a lot of approaches, but I was wondering what the idiomatic
Rails-y way of doing it is. Should I create a Weekday class? It
wouldn’t be backed by the db - that’s not localizable or DRY…

In your code, the idiomatic way is to use an array:

DAYS = %w(sunday monday tuesday wednesday thursday friday saturday)

You should override your accessors that otherwise return a number 0-6 to
instead return that DAYS[value] (or, more likely, value && DAYS[value]).
Now you can deal with days by string. (Probably a better choice is to
make
that an array of symbols and deal with them by symbol.) Once you get to
the
rendering phase, just have your local substitutions based on the
internal
symbols.

Any help appreciated.
–Greg

I’ve done a similar thing with Periods of time ( e.g. daily, weekly,
monthly ) where I wanted the value stored as an integer number of days.
To do this I created a Struct for Period and then set a constant
pointing to a hash of populated Periods.

hth,
-jc

Ok, for the display I made a new FormBuilder subclass and added a
select_weekday method. To get the localized weekday names, it does
this:

Date.new(2001,1,weekday_number+7).strftime("%A")

Someone please tell me a better way. :slight_smile:

It seems that Date#strftime doesn’t honor locale settings, which is
odd since strftime(3) does. So that code returns the same output as
just doing Date::DAYNAMES[weekday_number]. I’ll have to look into
some other way to get at the localized names…

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs