-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathenum.rb
More file actions
76 lines (59 loc) · 1.5 KB
/
enum.rb
File metadata and controls
76 lines (59 loc) · 1.5 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# Downside to enumerations expressed as tables:
# * Chained method calls that can fail, e.g. glass.color.name
# * Extra database joins (performance)
# * Can't quickly identify an instance, e.g. Color.find(3) => green
require 'rubygems'
require 'active_support'
module Enum
@@values = HashWithIndifferentAccess.new
module ClassMethods
# Return all possible color objects
def all
@@values.keys.collect { |label| self.class.new(label) }
end
end
def self.included(base)
base.extend ClassMethods
end
def initialize(label=nil)
if @@values[label].nil?
raise ArgumentError, "Invalid label #{label.inspect}"
end
@label = label
end
# Return the english name of this color (or nil if this is an unknown color)
def to_s
@@values[@label]
end
# Return the label for this color
def label
@label.to_sym
end
# Is this a valid color? (could be nil too)
def valid?
! @@values[@label].nil?
end
# Is this color nil? (as opposed to just not valid?)
def empty?
@label.nil?
end
# Value to use when hashing color objects
def hash
@label
end
# See if two colors are equivalent.
def ==(other_color)
@label == other_color.label
end
end
class Color
include Enum
@@values['dark_green'] = 'Dark Green'
@@values['sky_blue'] = 'Sky Blue'
@@values['brick_red'] = 'Brick Red'
end
class Flavor
include Enum
@@values['vanilla'] = 'Vanilla'
@@values['strawberry'] = 'Strawberry'
end