Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Ruby (http://www.velocityreviews.com/forums/f66-ruby.html)
-   -   Idiomatic Ruby: Enumerations (http://www.velocityreviews.com/forums/t828888-idiomatic-ruby-enumerations.html)

listrecv@gmail.com 02-21-2006 09:01 AM

Idiomatic Ruby: Enumerations
 
Hi. I'd appreciate comments/criticisms on the following approach &
code:

For some variables, we need to be able to choose from enumerations.
For instance, we track different choices on a webform - each has an
integer code, as well as some other properties. I want to implement a
class which these are made out of.

How's this?:

class TimeSlot

# Only use predefined
private_class_method :new

# The text description
attr_reader :text

# The integer code
attr_reader :code

# The legacy_id (key in a legacy database)
attr_reader :legacy_id

def initialize(text, code, legacy_id)
@text = text
@code = code
@legacy_id = legacy_id
end

MORNING = new('morning', 2, 1001)
AFTERNOON = new('morning', 3, 1002)
EVENING = new('evening', 4, 1003)
NIGHT = new('night', 5, 1004')

# This next line is unDRY, but I'm not sure how to eliminate
it.
# Perhaps instead of just listing the constansts, use a
register_value method which both defines the constant
# and adds it to the @@values - but I'm not sure how to
implement this
@@members = [MORNING, AFTERNOON, EVENING, NIGHT]

def self.from_code(c)
@@members.find { |t| t.code == c } || raise ArgumentError, "No
TimeSlot has code #{c}"
end

end

Also - we have several of these - how would I extract a common
Enumeration mixin? I'd like to be able to include Enumeration, much as
you include Singleton, to turn a class into an enumeration type along
these lines.



All times are GMT. The time now is 05:54 PM.

Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57