Class: Apiwork::Representation::Deserializer

Inherits:
Object
  • Object
show all
Defined in:
lib/apiwork/representation/deserializer.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(representation_class) ⇒ Deserializer

Returns a new instance of Deserializer.



12
13
14
# File 'lib/apiwork/representation/deserializer.rb', line 12

def initialize(representation_class)
  @representation_class = representation_class
end

Class Method Details

.deserialize(representation_class, payload) ⇒ Object



7
8
9
# File 'lib/apiwork/representation/deserializer.rb', line 7

def deserialize(representation_class, payload)
  new(representation_class).deserialize(payload)
end

Instance Method Details

#deserialize(payload) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/apiwork/representation/deserializer.rb', line 16

def deserialize(payload)
  if payload.is_a?(Array)
    payload.map { |hash| deserialize_hash(hash) }
  else
    deserialize_hash(payload)
  end
end

#deserialize_hash(hash) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/apiwork/representation/deserializer.rb', line 24

def deserialize_hash(hash)
  return hash unless hash.is_a?(Hash)

  result = hash.dup

  transform_type_columns(result)

  @representation_class.attributes.each do |name, attribute|
    next unless result.key?(name)

    result[name] = attribute.decode(result[name])
  end

  @representation_class.associations.each do |name, association|
    next unless result.key?(name)

    nested_representation_class = association.representation_class
    next unless nested_representation_class

    value = result[name]
    result[name] = if association.collection? && value.is_a?(Array)
                     value.map { |item| nested_representation_class.deserialize(item) }
                   elsif value.is_a?(Hash)
                     nested_representation_class.deserialize(value)
                   else
                     value
                   end
  end

  result
end