Class: Typed::Coercion::StructCoercer

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

Constant Summary collapse

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

Instance Method Summary collapse

Instance Method Details

#coerce(type:, value:) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/typed/coercion/struct_coercer.rb', line 18

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

  return Failure.new(CoercionError.new("Value of type '#{value.class}' cannot be coerced to #{type} Struct.")) unless value.is_a?(Hash)

  deserialization_result = T.cast(type, T::Types::Simple)
    .raw_type
    .deserialize_from(:hash, value)

  if deserialization_result.success?
    deserialization_result
  else
    Failure.new(CoercionError.new(deserialization_result.error.message))
  end
rescue ArgumentError, RuntimeError
  Failure.new(CoercionError.new("Given hash could not be coerced to #{type}."))
end

#used_for_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


11
12
13
14
15
# File 'lib/typed/coercion/struct_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::Struct)
end