Sha256: 9204f9f33f6c7c8bf70519f6071e4aa808017c8e12c6439456a7b4a9539b2b57

Contents?: true

Size: 1.35 KB

Versions: 8

Compression:

Stored size: 1.35 KB

Contents

# typed: strict

module Typed
  class Schema < T::Struct
    extend T::Sig
    include ActsAsComparable

    const :fields, T::Array[Field], default: []
    const :target, T.class_of(T::Struct)

    sig { params(struct: T.class_of(T::Struct)).returns(Typed::Schema) }
    def self.from_struct(struct)
      Typed::Schema.new(
        target: struct,
        fields: struct.props.map do |name, properties|
          Typed::Field.new(name:, type: properties[:type_object], default: properties.fetch(:default, nil))
        end
      )
    end

    sig { params(hash: Typed::HashSerializer::InputHash).returns(Typed::Serializer::DeserializeResult) }
    def from_hash(hash)
      Typed::HashSerializer.new(schema: self).deserialize(hash)
    end

    sig { params(json: String).returns(Typed::Serializer::DeserializeResult) }
    def from_json(json)
      Typed::JSONSerializer.new(schema: self).deserialize(json)
    end

    sig { params(field_name: Symbol, serializer: Field::InlineSerializer).returns(Schema) }
    def add_serializer(field_name, serializer)
      self.class.new(
        target: target,
        fields: fields.map do |field|
          if field.name == field_name
            Field.new(name: field.name, type: field.type, default: field.default, inline_serializer: serializer)
          else
            field
          end
        end
      )
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
sorbet-schema-0.9.2 lib/typed/schema.rb
sorbet-schema-0.9.1 lib/typed/schema.rb
sorbet-schema-0.9.0 lib/typed/schema.rb
sorbet-schema-0.8.0 lib/typed/schema.rb
sorbet-schema-0.7.2 lib/typed/schema.rb
sorbet-schema-0.7.1 lib/typed/schema.rb
sorbet-schema-0.7.0 lib/typed/schema.rb
sorbet-schema-0.6.0 lib/typed/schema.rb