Class: EnumType

Inherits:
ActiveModel::Type::Value
  • Object
show all
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

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

Raises:

  • (ArgumentError)


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