Class: Typed::YMLSerializer

Inherits:
Serializer show all
Defined in:
lib/typed/yml_serializer.rb

Constant Summary collapse

Input =
type_member { {fixed: String} }
Output =
type_member { {fixed: String} }

Constants inherited from Serializer

Serializer::DeserializeResult, Serializer::Params

Instance Attribute Summary

Attributes inherited from Serializer

#coercer_cache, #schema

Instance Method Summary collapse

Methods inherited from Serializer

#initialize

Constructor Details

This class inherits a constructor from Typed::Serializer

Instance Method Details

#deserialize(source) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/typed/yml_serializer.rb', line 12

def deserialize(source)
  parsed_yaml = YAML.safe_load(source, permitted_classes: [Date, Time], symbolize_names: true)
  return Failure.new(ParseError.new(format: :yml)) unless parsed_yaml.is_a?(Hash)

  creation_params = schema.fields.each_with_object(T.let({}, Params)) do |field, hsh|
    hsh[field.name] = parsed_yaml[field.name]
  end

  deserialize_from_creation_params(creation_params)
rescue Psych::SyntaxError, Psych::DisallowedClass
  Failure.new(ParseError.new(format: :yml))
end

#serialize(struct) ⇒ Object



26
27
28
29
30
# File 'lib/typed/yml_serializer.rb', line 26

def serialize(struct)
  return Failure.new(SerializeError.new("'#{struct.class}' cannot be serialized to target type of '#{schema.target}'.")) if struct.class != schema.target

  Success.new(YAML.dump(stringify_keys(serialize_from_struct(struct:, should_serialize_values: true))))
end