Module: FIRM::Serializable::JSON::ContainerPatch

Included in:
Array, Hash, OpenStruct, Set, Struct
Defined in:
lib/firm/serializer/json.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/firm/serializer/json.rb', line 56

def self.included(base)
  class << base
    def json_new(object, &block)
      # deserializing (anchor) object or alias
      if object.has_key?('*id')
        if FIRM::Serializable::Aliasing.restored?(self, object['*id'])
          # resolving an already restored anchor for this alias
          FIRM::Serializable::Aliasing.resolve_anchor(self, object['*id'])
        else
          # in case of cyclic references JSON will restore aliases before the anchors
          # so in this case we instantiate an instance here and register it as
          # the anchor; when the anchor is restored it will replace the contents of this
          # instance with the restored elements
          FIRM::Serializable::Aliasing.restore_anchor(object['*id'], self.new)
        end
      else
        instance = if object.has_key?('&id')
                     anchor_id = object['&id'] # extract anchor id
                     if FIRM::Serializable::Aliasing.restored?(self, anchor_id)
                       # in case of cyclic references an alias will already have restored the anchor instance
                       # (default constructed); retrieve that instance here for deserialization of properties
                       FIRM::Serializable::Aliasing.resolve_anchor(self, anchor_id)
                     else
                       # restore the anchor here with a newly instantiated instance
                       FIRM::Serializable::Aliasing.restore_anchor(anchor_id, self.new)
                     end
                   else
                     self.new
                   end
        block.call(instance)
        instance
      end
    end
    private :json_new
  end
end