Class: ActiveRecord::Enum::EnumType

Inherits:
Type::Value
  • Object
show all
Defined in:
lib/active_record/enum.rb

Overview

:nodoc:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, mapping, subtype, raise_on_invalid_values: true) ⇒ EnumType

Returns a new instance of EnumType.



173
174
175
176
177
178
# File 'lib/active_record/enum.rb', line 173

def initialize(name, mapping, subtype, raise_on_invalid_values: true)
  @name = name
  @mapping = mapping
  @subtype = subtype
  @_raise_on_invalid_values = raise_on_invalid_values
end

Instance Attribute Details

#subtypeObject (readonly)

Returns the value of attribute subtype.



210
211
212
# File 'lib/active_record/enum.rb', line 210

def subtype
  @subtype
end

Instance Method Details

#assert_valid_value(value) ⇒ Object



202
203
204
205
206
207
208
# File 'lib/active_record/enum.rb', line 202

def assert_valid_value(value)
  return unless @_raise_on_invalid_values

  unless value.blank? || mapping.has_key?(value) || mapping.has_value?(value)
    raise ArgumentError, "'#{value}' is not a valid #{name}"
  end
end

#cast(value) ⇒ Object



180
181
182
183
184
185
186
187
188
# File 'lib/active_record/enum.rb', line 180

def cast(value)
  if mapping.has_key?(value)
    value.to_s
  elsif mapping.has_value?(value)
    mapping.key(value)
  else
    value.presence
  end
end

#deserialize(value) ⇒ Object



190
191
192
# File 'lib/active_record/enum.rb', line 190

def deserialize(value)
  mapping.key(subtype.deserialize(value))
end

#serializable?(value, &block) ⇒ Boolean

Returns:

  • (Boolean)


198
199
200
# File 'lib/active_record/enum.rb', line 198

def serializable?(value, &block)
  subtype.serializable?(mapping.fetch(value, value), &block)
end

#serialize(value) ⇒ Object



194
195
196
# File 'lib/active_record/enum.rb', line 194

def serialize(value)
  subtype.serialize(mapping.fetch(value, value))
end