Sha256: 8eb93ede96613b569c96985e7aafada1ff47cb3b68f97c2205a486d19ee4b121

Contents?: true

Size: 909 Bytes

Versions: 4

Compression:

Stored size: 909 Bytes

Contents

# typed: strict

module Typed
  module Coercion
    class StructCoercer < Coercer
      extend T::Generic

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

      sig { override.params(type: T::Class[T.anything]).returns(T::Boolean) }
      def used_for_type?(type)
        !!(type < T::Struct)
      end

      sig { override.params(field: Field, value: Value).returns(Result[Target, CoercionError]) }
      def coerce(field:, value:)
        type = field.type

        return Failure.new(CoercionError.new("Field type must inherit from T::Struct for Struct coercion.")) unless type < T::Struct
        return Failure.new(CoercionError.new("Value must be a Hash for Struct coercion.")) unless value.is_a?(Hash)

        Success.new(type.from_hash!(HashTransformer.new.deep_stringify_keys(value)))
      rescue ArgumentError => e
        Failure.new(CoercionError.new(e.message))
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
sorbet-schema-0.3.0 lib/typed/coercion/struct_coercer.rb
sorbet-schema-0.2.2 lib/typed/coercion/struct_coercer.rb
sorbet-schema-0.2.1 lib/typed/coercion/struct_coercer.rb
sorbet-schema-0.2.0 lib/typed/coercion/struct_coercer.rb