Module: Mongoid::Serialization

Extended by:
ActiveSupport::Concern
Included in:
Components
Defined in:
lib/mongoid/serialization.rb

Overview

This module provides the extra behaviour for including relations in JSON and XML serialization.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.mongoize(object, klass = Object) ⇒ Object

Serialize the provided object into a Mongo friendly value, using the field serialization method for the passed in type. If no type is given then we assume generic object serialization, which just returns the value itself.

Examples:

Mongoize the object.

Mongoid::Serialization.mongoize(time, Time)

Parameters:

  • object (Object)

    The object to convert.

  • klass (Class) (defaults to: Object)

    The type of the object.

Returns:

  • (Object)

    The converted object.

Since:

  • 2.1.0



79
80
81
# File 'lib/mongoid/serialization.rb', line 79

def mongoize(object, klass = Object)
  Fields::Mappings.for(klass).instantiate(:mongoize).serialize(object)
end

Instance Method Details

#serializable_hash(options = nil) ⇒ Hash

Gets the document as a serializable hash, used by ActiveModel’s JSON serializer.

Examples:

Get the serializable hash.

document.serializable_hash

Get the serializable hash with options.

document.serializable_hash(:include => :addresses)

Parameters:

  • options (Hash) (defaults to: nil)

    The options to pass.

Options Hash (options):

  • :include (Symbol)

    What relations to include.

  • :only (Symbol)

    Limit the fields to only these.

  • :except (Symbol)

    Dont include these fields.

  • :methods (Symbol)

    What methods to include.

Returns:

  • (Hash)

    The document, ready to be serialized.

Since:

  • 2.0.0.rc.6



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/mongoid/serialization.rb', line 28

def serializable_hash(options = nil)
  options ||= {}

  only   = Array.wrap(options[:only]).map(&:to_s)
  except = Array.wrap(options[:except]).map(&:to_s)

  except |= ['_type'] unless Mongoid.include_type_for_serialization

  field_names = fields.keys.map { |field| field.to_s }
  attribute_names = (as_document.keys + field_names).sort
  if only.any?
    attribute_names &= only
  elsif except.any?
    attribute_names -= except
  end

  method_names = Array.wrap(options[:methods]).map do |name|
    name.to_s if respond_to?(name)
  end.compact

  {}.tap do |attrs|
    (attribute_names + method_names).each do |name|
      if relations.has_key?(name)
        value = send(name)
        attrs[name] = value ? value.serializable_hash(options) : nil
      elsif attribute_names.include?(name) && !fields.has_key?(name)
        attrs[name] = read_attribute(name)
      else
        attrs[name] = send(name)
      end
    end
    serialize_relations(attrs, options) if options[:include]
  end
end