Class: Pyper::Pipes::Model::VirtusDeserializer

Inherits:
Object
  • Object
show all
Defined in:
lib/pyper/pipes/model/virtus_deserializer.rb

Overview

Provides a way to deserialize serialized fields from an item. This is intended to be used with a Virtus model class, and will use the attribute names and type information from that model to determine how to deserialize.

All serialization is as JSON.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attribute_set) ⇒ VirtusDeserializer

Returns a new instance of VirtusDeserializer.

Parameters:

  • attribute_set (Virtus::AttributeSet)

    A Virtus AttributeSet



14
15
16
# File 'lib/pyper/pipes/model/virtus_deserializer.rb', line 14

def initialize(attribute_set)
  @type_mapping = Hash[attribute_set.map { |attr| [attr.name.to_s, attr.type.primitive] }]
end

Instance Attribute Details

#type_mappingObject (readonly)

Returns the value of attribute type_mapping.



11
12
13
# File 'lib/pyper/pipes/model/virtus_deserializer.rb', line 11

def type_mapping
  @type_mapping
end

Instance Method Details

#deserialize(value, type) ⇒ Object



32
33
34
35
36
37
# File 'lib/pyper/pipes/model/virtus_deserializer.rb', line 32

def deserialize(value, type)
  if type == Array || type == Hash then JSON.parse(value)
  elsif type == Integer then value.to_i
  elsif type == Float then value.to_f
  else value end
end

#pipe(items, status = {}) ⇒ Enumerator<Hash>

Returns A list of items, deserialized according to the type mapping.

Parameters:

  • items (Enumerator<Hash>)

    A list of items

  • status (Hash) (defaults to: {})

    The mutable status field

Returns:

  • (Enumerator<Hash>)

    A list of items, deserialized according to the type mapping



21
22
23
24
25
26
27
28
29
30
# File 'lib/pyper/pipes/model/virtus_deserializer.rb', line 21

def pipe(items, status = {})
  items.map do |item|
    new_item = item.dup
    type_mapping.each do |field, type|
      new_item[field] = deserialize(new_item[field], type) if new_item[field]
    end

    new_item
  end
end