Module: MemoryRecord::Serialization

Defined in:
lib/memory_record/memory_record/serialization.rb

Overview

Reference: ActiveModel::Serializers::JSON github.com/rails/rails/blob/0605f45ab323331b06dde3ed16838f56f141ca3f/activemodel/lib/active_model/serialization.rb The original code and the implementation are slightly different

Instance Method Summary collapse

Instance Method Details

#as_json(options = {}) ⇒ Object



39
40
41
# File 'lib/memory_record/memory_record/serialization.rb', line 39

def as_json(options = {})
  serializable_hash(options)
end

#serializable_hash(options = nil) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/memory_record/memory_record/serialization.rb', line 11

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

  keys = attributes.keys
  if only = options[:only]
    keys &= Array(only)
  elsif except = options[:except]
    keys -= Array(except)
  end
  keys += Array(options[:methods])

  hash = {}
  keys.each { |e| hash[e] = send(e) }
  Array(options[:methods]).each { |e| hash[e] = read_attribute_for_serialization(e) }

  serializable_add_includes(options) do |association, records, opts|
    hash[association] = -> {
      if records.respond_to?(:to_ary)
        records.to_ary.map { |a| a.as_json(opts) }
      else
        records.as_json(opts)
      end
    }.call
  end

  hash
end