Class: EnumType
- Inherits:
-
ActiveModel::Type::Value
- Object
- ActiveModel::Type::Value
- EnumType
- Defined in:
- app/types/enum_type.rb
Overview
Custom ActiveRecord/ActiveModel attribute type that constrains a
string column to a fixed allow-list. Raises ArgumentError on any
value not in the list. Used for jsonb-backed columns where we need
stronger validation than validates :foo, inclusion: { in: ... }
(e.g. when the value is set inside a nested struct).
Instance Method Summary collapse
- #cast(value) ⇒ Object
- #deserialize(value) ⇒ Object
-
#initialize(allowed_values) ⇒ EnumType
constructor
A new instance of EnumType.
- #serialize(value) ⇒ Object
Constructor Details
#initialize(allowed_values) ⇒ EnumType
Returns a new instance of EnumType.
8 9 10 |
# File 'app/types/enum_type.rb', line 8 def initialize(allowed_values) @allowed_values = allowed_values end |
Instance Method Details
#cast(value) ⇒ Object
12 13 14 15 16 17 |
# File 'app/types/enum_type.rb', line 12 def cast(value) return nil if value.blank? raise ArgumentError, "Invalid value: #{value}" unless @allowed_values.include?(value) value end |
#deserialize(value) ⇒ Object
23 24 25 |
# File 'app/types/enum_type.rb', line 23 def deserialize(value) cast(value) end |
#serialize(value) ⇒ Object
19 20 21 |
# File 'app/types/enum_type.rb', line 19 def serialize(value) cast(value) end |