Class: Mongoid::NestedSerialization::Serializer

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

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ Serializer

Returns a new instance of Serializer.



7
8
9
# File 'lib/mongoid/nested_serialization/serializer.rb', line 7

def initialize(object)
  @object = object
end

Instance Method Details

#to_hash(embedded_contents = nil) ⇒ Object

spits out a hash which can be used to relocate the object in the collection tree



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/mongoid/nested_serialization/serializer.rb', line 20

def to_hash(embedded_contents = nil)
  if object.embedded?
    # select the relation for the parent object
    parent_relation = object.relations.select do |k,v|
      v.macro == :embedded_in && v.class_name == object._parent.class.name
    end.values.first
    # embed this in the parent's hash
    result = {
      association: parent_relation.inverse_of,
      id: object.id
    }
    result = result.merge(embedded: embedded_contents) if embedded_contents
    self.class.new(object._parent).to_hash(result)
  else # !embedded?
    result = { class_name: object.class.name, id: object.id }
    result[:embedded] = embedded_contents if embedded_contents
    result
  end
end

#to_jsonObject

spits out a JSON hash which can be used to relocate the object in the collection tree



13
14
15
16
# File 'lib/mongoid/nested_serialization/serializer.rb', line 13

def to_json
  # convert the result to JSON
  MultiJson.dump(to_hash)
end