Module: EnumType
- Defined in:
- lib/enum_type.rb
Overview
Adds the @enum_type@ method to a model.
Instance Method Summary collapse
-
#enum_type(field, ..., options = {}) ⇒ Object
Defines a field whose type is an enumeration.
Instance Method Details
#enum_type(field, ..., options = {}) ⇒ Object
Defines a field whose type is an enumeration. Values are stored as strings in the backend (or your database’s enumerated type), however in the Rails level they are represented as symbols.
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/enum_type.rb', line 28 def enum_type(*fields) = fields. fields.each do |field| define_method field do value = read_attribute(field) value ? value.to_sym : value end define_method :"#{field}=" do |value| write_attribute field, value.try(:to_s) end validates_presence_of(field) unless [:allow_nil] validates_inclusion_of(field, in: [:values].map(&:to_sym), allow_nil: [:allow_nil]) if [:values] end end |