Class: Typed::Schema

Inherits:
T::Struct show all
Extended by:
T::Sig
Includes:
ActsAsComparable
Defined in:
lib/typed/schema.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from T::Struct

deserialize_from, schema, #serialize_to, serializer

Class Method Details

.from_struct(struct) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/typed/schema.rb', line 12

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

Instance Method Details

#add_serializer(field_name, serializer) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/typed/schema.rb', line 32

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

#from_hash(hash) ⇒ Object



22
23
24
# File 'lib/typed/schema.rb', line 22

def from_hash(hash)
  Typed::HashSerializer.new(schema: self).deserialize(hash)
end

#from_json(json) ⇒ Object



27
28
29
# File 'lib/typed/schema.rb', line 27

def from_json(json)
  Typed::JSONSerializer.new(schema: self).deserialize(json)
end