Class: Skit::Serialization::Processor::Struct
- Extended by:
- T::Sig
- Defined in:
- lib/skit/serialization/processor/struct.rb
Class Method Summary collapse
Instance Method Summary collapse
- #deserialize(value, path: Path.new) ⇒ Object
-
#initialize(type_spec, registry:) ⇒ Struct
constructor
A new instance of Struct.
- #serialize(value, path: Path.new) ⇒ Object
- #traverse(value, path: Path.new, &blk) ⇒ Object
Constructor Details
#initialize(type_spec, registry:) ⇒ Struct
18 19 20 21 22 23 24 25 |
# File 'lib/skit/serialization/processor/struct.rb', line 18 def initialize(type_spec, registry:) super unless type_spec.is_a?(Class) && type_spec < T::Struct raise ArgumentError, "Expected T::Struct, got #{type_spec}" end @struct_class = T.let(type_spec, T.class_of(T::Struct)) end |
Class Method Details
.handles?(type_spec) ⇒ Boolean
11 12 13 14 15 |
# File 'lib/skit/serialization/processor/struct.rb', line 11 def self.handles?(type_spec) return false unless type_spec.is_a?(Class) !!(type_spec < T::Struct) end |
Instance Method Details
#deserialize(value, path: Path.new) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/skit/serialization/processor/struct.rb', line 43 def deserialize(value, path: Path.new) return value if value.is_a?(@struct_class) raise DeserializeError.new("Expected Hash, got #{value.class}", path: path) unless value.is_a?(::Hash) symbolized = value.transform_keys(&:to_sym) deserialized = @struct_class.props.each_with_object({}) do |(name, prop_def), hash| next unless symbolized.key?(name) prop_value = symbolized[name] prop_type = prop_def[:type_object] processor = @registry.processor_for(prop_type) hash[name] = processor.deserialize(prop_value, path: path.append(name.to_s)) end @struct_class.new(**deserialized) end |
#serialize(value, path: Path.new) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/skit/serialization/processor/struct.rb', line 28 def serialize(value, path: Path.new) unless value.is_a?(@struct_class) raise SerializeError.new("Expected #{@struct_class}, got #{value.class}", path: path) end @struct_class.props.each_with_object({}) do |(name, prop_def), hash| prop_value = value.public_send(name) prop_type = prop_def[:type_object] processor = @registry.processor_for(prop_type) hash[name.to_s] = processor.serialize(prop_value, path: path.append(name.to_s)) end end |
#traverse(value, path: Path.new, &blk) ⇒ Object
69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/skit/serialization/processor/struct.rb', line 69 def traverse(value, path: Path.new, &blk) super return unless value.is_a?(@struct_class) @struct_class.props.each do |name, prop_def| prop_value = value.public_send(name) prop_type = prop_def[:type_object] processor = @registry.processor_for(prop_type) processor.traverse(prop_value, path: path.append(name.to_s), &blk) end end |