Class: Skit::Serialization::Processor::Tuple

Inherits:
Base
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/skit/serialization/processor/tuple.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type_spec, registry:) ⇒ Tuple

Returns a new instance of Tuple.



16
17
18
19
20
21
22
23
# File 'lib/skit/serialization/processor/tuple.rb', line 16

def initialize(type_spec, registry:)
  super
  unless type_spec.is_a?(T::Types::FixedArray)
    raise ArgumentError, "Expected T::Types::FixedArray, got #{type_spec.class}"
  end

  @element_types = T.let(type_spec.types, T::Array[T.untyped])
end

Class Method Details

.handles?(type_spec) ⇒ Boolean

Returns:



11
12
13
# File 'lib/skit/serialization/processor/tuple.rb', line 11

def self.handles?(type_spec)
  type_spec.is_a?(T::Types::FixedArray)
end

Instance Method Details

#deserialize(value, path: Path.new) ⇒ Object

Raises:



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/skit/serialization/processor/tuple.rb', line 41

def deserialize(value, path: Path.new)
  raise DeserializeError.new("Expected Array, got #{value.class}", path: path) unless value.is_a?(::Array)

  value.each_with_index.map do |item, index|
    element_type = @element_types[index]
    if element_type
      processor = @registry.processor_for(element_type)
      processor.deserialize(item, path: path.append(index))
    else
      item
    end
  end
end

#serialize(value, path: Path.new) ⇒ Object

Raises:



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/skit/serialization/processor/tuple.rb', line 26

def serialize(value, path: Path.new)
  raise SerializeError.new("Expected Array, got #{value.class}", path: path) unless value.is_a?(::Array)

  value.each_with_index.map do |item, index|
    element_type = @element_types[index]
    if element_type
      processor = @registry.processor_for(element_type)
      processor.serialize(item, path: path.append(index))
    else
      item
    end
  end
end

#traverse(value, path: Path.new, &blk) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/skit/serialization/processor/tuple.rb', line 62

def traverse(value, path: Path.new, &blk)
  super

  return unless value.is_a?(::Array)

  value.each_with_index do |item, index|
    element_type = @element_types[index]
    if element_type
      processor = @registry.processor_for(element_type)
      processor.traverse(item, path: path.append(index), &blk)
    end
  end
end