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
|
# File 'lib/active_record-enumerated_model/enumerated_model.rb', line 8
def create_enumeration_constants(enumeration_attribute = :name, options = {:force => false})
@enumeration_attribute = enumeration_attribute
@enumerated_constants = [] if @enumerated_constants.blank?
clear_existing_constants if options[:force]
attribute = enumeration_attribute.to_s
self.all.each do |instance|
unless instance.attributes.include?(attribute)
raise UnknownAttributeError.new("Tried to create constants on the #{attribute} attribute, but it doesn't exist on this model")
end
value = instance.attributes[attribute]
if value.blank?
raise NilConstantError.new("Encountered a nil value on the #{attribute} attribute and can't create a constant")
end
const = ActiveRecord::EnumeratedModel.constant_friendly_string(value)
if self.const_defined?(const)
if options[:force]
self.send(:remove_const, const)
else
raise RuntimeError.new("Constant #{self.to_s}::#{const} has already been defined")
end
end
self.const_set(const, instance)
@enumerated_constants << const
end
end
|