Module: Mongoid::Serializable

Extended by:
ActiveSupport::Concern
Included in:
Composable
Defined in:
lib/mongoid/serializable.rb

Overview

This module provides the extra behavior for including associations in JSON and XML serialization.

Instance Method Summary collapse

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):

  • :except (Symbol | String | Array<Symbol | String>)

    Do not include these field(s).

  • :include (Symbol | String | Array<Symbol | String>)

    Which association(s) to include.

  • :only (Symbol | String | Array<Symbol | String>)

    Limit the field(s) to only these.

  • :methods (Symbol | String | Array<Symbol | String>)

    What methods to include.

Returns:

  • (Hash)

    The document, ready to be serialized.



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/mongoid/serializable.rb', line 47

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

  names = field_names(options)

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

  (names + method_names).each do |name|
    without_autobuild do
      serialize_attribute(attrs, name, names, options)
    end
  end
  serialize_relations(attrs, options) if options[:include]
  attrs
end