Class: Pyper::Pipes::Model::AttributeSerializer

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

Overview

Provides a way to serialize attributes to JSON.

Instance Method Summary collapse

Instance Method Details

#force_encode_to_UTF8(value) ⇒ Object



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

def force_encode_to_UTF8(value)
  case value
  when Array
    value.map { |v| force_encode_to_UTF8(v) }
  when Hash
    Hash[value.map { |k,v| [k, force_encode_to_UTF8(v)] }]
  when String
    value.dup.force_encoding('UTF-8')
  else
    value
  end
end

#pipe(attributes, status = {}) ⇒ Hash

Returns The serialized attributes.

Parameters:

  • attributes (Hash)

    Unserialized attributes

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

    The mutable status field

Returns:

  • (Hash)

    The serialized attributes



10
11
12
13
14
15
16
17
18
19
# File 'lib/pyper/pipes/model/attribute_serializer.rb', line 10

def pipe(attributes, status = {})
  attributes.each_with_object({}) do |attr, serialized_attrs|
    value = force_encode_to_UTF8(attr.last)
    serialized_attrs[attr.first] = case value
                                   when Array, Hash then JSON.generate(value)
                                   when DateTime then value.to_time
                                   else value
                                   end
  end
end