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
76
77
78
79
80
81
82
83
84
|
# File 'lib/enumize_mongoid.rb', line 5
def self.included(klass)
klass.instance_eval do
def enumize(values, create_constants: false)
@@value_map = create_value_map(values)
if create_constants
const_set('VALUES', @@value_map)
@@value_map.each do |key, value|
const_set(key.to_s.upcase, value)
end
end
end
def create_value_map(opts)
return opts if opts.is_a? Hash
return Hash[opts.zip(0...opts.size)] if opts.is_a? Array
raise 'Not supported type'
end
def value_of(value)
@@value_map.invert[value]
end
def demongoize(object)
new(value_of(object))
end
def mongoize(object)
case object
when self then object.mongoize
when Symbol then new(object).mongoize
else object
end
end
def evolve(object)
case object
when self then object.mongoize
when Symbol then mongoize(object)
else object
end
end
end
klass.class_eval do
attr_reader :value
def initialize(value)
@value = value
end
def ==(obj)
case obj
when Symbol then obj == value
when self.class then obj.value == value
when Numeric then obj == @@value_map[value]
else false
end
end
def mongoize
@@value_map[value]
end
def to_s
"<#{self.class}|#{value}>"
end
end
end
|