Class: SimplySerializable::Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/simply_serializable/serializer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes: [], cache: {}, except: nil, include_readable_instance_variables: true, method_prefix: :serialize, object:, only: nil) ⇒ Serializer

Returns a new instance of Serializer.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/simply_serializable/serializer.rb', line 10

def initialize(
  attributes: [],
  cache: {},
  except: nil,
  include_readable_instance_variables: true,
  method_prefix: :serialize,
  object:,
  only: nil
)
  @object = object
  @attributes = attributes
  @include_readable_instance_variables = include_readable_instance_variables
  @except = except&.map(&:to_sym)
  @only = only&.map(&:to_sym)
  @method_prefix = method_prefix
  @cache = cache
  @cache[cache_key] = nil
  @serialized = false

  populate_attributes
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



5
6
7
# File 'lib/simply_serializable/serializer.rb', line 5

def attributes
  @attributes
end

#exceptObject (readonly)

Returns the value of attribute except.



5
6
7
# File 'lib/simply_serializable/serializer.rb', line 5

def except
  @except
end

#objectObject (readonly)

Returns the value of attribute object.



5
6
7
# File 'lib/simply_serializable/serializer.rb', line 5

def object
  @object
end

#onlyObject (readonly)

Returns the value of attribute only.



5
6
7
# File 'lib/simply_serializable/serializer.rb', line 5

def only
  @only
end

Instance Method Details

#cacheObject



32
33
34
35
# File 'lib/simply_serializable/serializer.rb', line 32

def cache
  serialize unless @serialized
  @cache
end

#deep_serialize(obj) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/simply_serializable/serializer.rb', line 37

def deep_serialize(obj)
  case obj
  when FalseClass, Float, nil, Integer, String, Symbol, TrueClass
    obj
  when Array
    obj.map { |v| deep_serialize(v) }
  when Hash
    Hash[obj.map { |k, v| [deep_serialize(k), deep_serialize(v)] }]
  when Module
    obj.name
  else
    serialize_object(obj)
  end
end

#serializeObject



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/simply_serializable/serializer.rb', line 52

def serialize
  @serialize ||= begin
    @serialized = true
    ret = deep_serialize(object_value_hash)

    cache[cache_key] = ret
    {
      root: cache_key,
      objects: cache
    }
  end
end

#to_sObject



65
66
67
# File 'lib/simply_serializable/serializer.rb', line 65

def to_s
  @to_s ||= serialize.to_s
end