class Mongoid::NestedSerialization::Serializer

Public Class Methods

new(object) click to toggle source
# File lib/mongoid/nested_serialization/serializer.rb, line 7
def initialize(object)
  @object = object
end

Public Instance Methods

to_hash(embedded_contents = nil) click to toggle source

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

# 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_json() click to toggle source

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

# File lib/mongoid/nested_serialization/serializer.rb, line 13
def to_json
  # convert the result to JSON
  MultiJson.dump(to_hash)
end

Private Instance Methods

object() click to toggle source
# File lib/mongoid/nested_serialization/serializer.rb, line 41
def object
  @object
end