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/mongo_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
|