Class: Defaultable::Serialization

Inherits:
Object
  • Object
show all
Defined in:
lib/defaultable/serialization.rb

Instance Method Summary collapse

Instance Method Details

#dump(obj) ⇒ Object

Called to convert from ruby object to serialized data.

Raises:

  • (TypeError)


20
21
22
23
24
25
26
27
28
29
# File 'lib/defaultable/serialization.rb', line 20

def dump(obj)
  raise TypeError, "Serialization failed: Object is not of type #{self.class.settings_class.name}." if !obj.is_a?(self.class.settings_class) && !obj.nil?

  # We need to use the registry because we don't want to store defaults that weren't overwritten
  if obj.nil?
    self.class.settings_class.new
  else
    obj.class.new(obj.registry.as_hash).to_yaml if obj
 end
end

#load(data) ⇒ Object

Called to deserialize data to ruby object.



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/defaultable/serialization.rb', line 6

def load(data)
  if data
    obj = raw_load(data)

    raise TypeError, "Deserialized object is not of type #{self.class.settings_class.name}. Got #{obj.class}" unless obj.is_a?(self.class.settings_class)

    # The reason we do the following is because defaults may have changed
    # after the point of serialization. To avoid not having them, we instantiate the class
    # again, we the previous values. This prevents not having data.
    obj.class.new(obj.as_hash)
  end
end

#raw_load(data) ⇒ Object



31
32
33
# File 'lib/defaultable/serialization.rb', line 31

def raw_load(data)
  YAML.load(data)
end