Module: ActiveRecord::EnumeratedModel::ClassMethods
- Defined in:
- lib/active_record-enumerated_model/enumerated_model.rb
Instance Method Summary collapse
- #bypass_readonly(&block) ⇒ Object
- #clear_existing_constants ⇒ Object
- #create_enumeration_constants(enumeration_attribute = :name, options = {:force => false}) ⇒ Object
Instance Method Details
#bypass_readonly(&block) ⇒ Object
45 46 47 48 49 50 51 |
# File 'lib/active_record-enumerated_model/enumerated_model.rb', line 45 def bypass_readonly(&block) ActiveRecord::ReadonlyModel.bypass do yield end # regenerate constants create_enumeration_constants(@enumeration_attribute, :force => true) end |
#clear_existing_constants ⇒ Object
35 36 37 38 39 40 41 42 43 |
# File 'lib/active_record-enumerated_model/enumerated_model.rb', line 35 def clear_existing_constants unless @enumerated_constants.blank? @enumerated_constants.each do |existing_constant| if self.const_defined?(existing_constant) self.send(:remove_const, existing_constant) end end end end |
#create_enumeration_constants(enumeration_attribute = :name, options = {:force => false}) ⇒ Object
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, = {:force => false}) @enumeration_attribute = enumeration_attribute @enumerated_constants = [] if @enumerated_constants.blank? clear_existing_constants if [: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 [: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 |