Module: Ripple::Serialization

Extended by:
ActiveSupport::Concern
Includes:
ActiveModel::Serializers::JSON
Defined in:
lib/ripple/serialization.rb

Overview

Provides methods for serializing Ripple documents to external formats (e.g. JSON). By default, embedded documents will be included in the resulting format.

Instance Method Summary collapse

Instance Method Details

#serializable_hash(options = nil) ⇒ Hash

Creates a Hash suitable for conversion to an external format.

Parameters:

  • options (Hash) (defaults to: nil)

    (nil) serialization options

Options Hash (options):

  • :only (Array<Symbol>)

    emit only the specified attributes

  • :except (Array<Symbol>)

    omit the specified attributes

  • :include (Array<Symbol>, Hash)

    include the specified associations (with or without extra options). This defaults to all embedded associations.

Returns:

  • (Hash)

    a hash of attributes and embedded documents



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/ripple/serialization.rb', line 35

def serializable_hash(options=nil)
  options = options.try(:clone) || {}

  unless options.has_key?(:include)
    options[:include] = self.class.embedded_associations.map(&:name)
  end

  hash = super(options)

  hash['key'] = key if respond_to?(:key) && key.present? && (!options[:except] || !options[:except].map(&:to_s).include?("key"))

  serializable_add_includes(options) do |association, records, opts|
    hash[association.to_s] = records.is_a?(Enumerable) ? records.map {|r| r.serializable_hash(opts) } : records.serializable_hash(opts)
  end
  hash
end