Module: MarkMapper::Plugins::Serialization

Extended by:
ActiveSupport::Concern
Included in:
Document, EmbeddedDocument
Defined in:
lib/mark_mapper/plugins/serialization.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#serializable_attributesObject


16
17
18
# File 'lib/mark_mapper/plugins/serialization.rb', line 16

def serializable_attributes
  attributes.keys.map { |k| k.to_s } + ['id'] - ['_id']
end

#serializable_hash(options = nil) ⇒ Object


20
21
22
23
24
25
26
27
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
# File 'lib/mark_mapper/plugins/serialization.rb', line 20

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

  options[:only]   = Array.wrap(options[:only]).map { |k| k.to_s }
  options[:except] = Array.wrap(options[:except]).map { |k| k.to_s }

  attribute_names = serializable_attributes

  if options[:only].any?
    attribute_names &= options[:only]
  elsif options[:except].any?
    attribute_names -= options[:except]
  end

  attribute_names += Array.wrap(options[:methods]).map { |m| m.to_s }.select do |method|
    respond_to?(method)
  end

  hash = attribute_names.sort.inject({}) do |hash, name|
    value = send(name)
    hash[name] = if value.is_a?(Array)
      value.map {|v| v.respond_to?(:serializable_hash) ? v.serializable_hash : v }
    elsif value.respond_to?(:serializable_hash)
      value.serializable_hash
    else
      value
    end
    hash
  end

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

  hash
end

#to_xml(options = {}, &block) ⇒ Object


59
60
61
# File 'lib/mark_mapper/plugins/serialization.rb', line 59

def to_xml(options = {}, &block)
  XmlSerializer.new(self, options).serialize(&block)
end