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
|
# File 'lib/enumerate/model.rb', line 3
def enumerate(attribute, vals={}, opts={})
validates_inclusion_of attribute, :in => vals, :allow_nil => !!opts[:allow_nil]
if self.columns_hash[attribute.to_s].nil?
raise "Column '#{attribute}' does not exist in #{self.class.name}"
else
col_type = self.columns_hash[attribute.to_s].type
end
const_hash_name = attribute.to_s.pluralize.upcase
if col_type == :string
vals = Hash[vals.zip vals.map{ |s| s.to_s }] if vals.kind_of?(Array)
elsif col_type == :integer
vals = Hash[vals.zip (0...vals.size)] if vals.kind_of?(Array)
else
raise "Unsupported column type for enumeration :#{attribute} in #{self.class}!"
end
raise "Unsupported values datatype for enumeration :#{attribute} in #{self.class}!" if !vals.kind_of?(Hash)
const_set(const_hash_name, vals)
setup_accessors(const_hash_name, attribute)
setup_predicates(vals, attribute)
end
|