Class: Typed::Coercion::EnumCoercer

Inherits:
Coercer
  • Object
show all
Extended by:
T::Generic
Defined in:
lib/typed/coercion/enum_coercer.rb

Constant Summary collapse

Target =
type_member { {fixed: T::Enum} }

Instance Method Summary collapse

Instance Method Details

#coerce(type:, value:) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/typed/coercion/enum_coercer.rb', line 18

def coerce(type:, value:)
  return Failure.new(CoercionError.new("Field type must inherit from T::Enum for Enum coercion.")) unless used_for_type?(type)

  Success.new(T.cast(type, T::Types::Simple).raw_type.from_serialized(value))
rescue KeyError => e
  Failure.new(CoercionError.new(e.message))
end

#used_for_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


11
12
13
14
15
# File 'lib/typed/coercion/enum_coercer.rb', line 11

def used_for_type?(type)
  return false unless type.respond_to?(:raw_type)

  !!(T.cast(type, T::Types::Simple).raw_type < T::Enum)
end