Class: Typed::Coercion::TypedArrayCoercer

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

Constant Summary collapse

Target =
type_member { {fixed: T::Array[T.untyped]} }

Instance Method Summary collapse

Instance Method Details

#coerce(type:, value:) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/typed/coercion/typed_array_coercer.rb', line 16

def coerce(type:, value:)
  return Failure.new(CoercionError.new("Field type must be a T::Array.")) unless used_for_type?(type)
  return Failure.new(CoercionError.new("Value must be an Array.")) unless value.is_a?(Array)

  return Success.new(value) if type.recursively_valid?(value)

  coerced_results = value.map do |item|
    Coercion.coerce(type: T.cast(type, T::Types::TypedArray).type, value: item)
  end

  if coerced_results.all?(&:success?)
    Success.new(coerced_results.map(&:payload))
  else
    Failure.new(CoercionError.new(coerced_results.select(&:failure?).map(&:error).map(&:message).join(" | ")))
  end
end

#used_for_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/typed/coercion/typed_array_coercer.rb', line 11

def used_for_type?(type)
  type.is_a?(T::Types::TypedArray)
end