Module: FIRM::Serializable::JSON::SerializeInstanceMethods

Included in:
ID, SerializeInstanceMethods
Defined in:
lib/firm/serializer/json.rb

Overview

extend instance serialization methods

Instance Method Summary collapse

Instance Method Details

#as_jsonObject



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/firm/serializer/json.rb', line 248

def as_json(*)
  json_data = {
    ::JSON.create_id => self.class.name
  }
  if (anchor = Serializable::Aliasing.get_anchor(self))
    anchor_data = Serializable::Aliasing.get_anchor_data(self)
    # retroactively insert the anchor in the anchored instance's serialization data
    anchor_data['&id'] = anchor unless anchor_data.has_key?('&id')
    json_data['*id'] = anchor
  else
    # register anchor object **before** serializing properties to properly handle cycling (bidirectional
    # references)
    Serializable::Aliasing.register_anchor_object(self, json_data)
    data = for_serialize({})
    unless data.empty?
      json_data['data'] = data
      json_data['data'].transform_values! { |v| v.respond_to?(:as_json) ? v.as_json : v }
    end
  end
  json_data
end