forked from elliotcm/light_mongo
/
hash_serializer.rb
74 lines (59 loc) · 2.38 KB
/
hash_serializer.rb
1
2
3
4
5
6
7
8
9
10
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
require 'mongo'
module LightMongo
module Document
module Serialization
class HashSerializer
class <<self
def dump(object_to_serialize, current_depth=0)
case object_to_serialize
when Array
return serialize_array(object_to_serialize, current_depth)
when Hash
return serialize_hash(object_to_serialize, current_depth)
else
return serialize_object(object_to_serialize, current_depth)
end
end
def serialize_array(object_to_serialize, current_depth)
object_to_serialize.map do |entry|
Serializer.serialize(entry, current_depth + 1)
end
end
def serialize_hash(object_to_serialize, current_depth)
outbound_hash = {}
object_to_serialize.each_pair do |key, entry|
outbound_hash[key] = Serializer.serialize(entry, current_depth + 1)
end
outbound_hash
end
def serialize_object(object_to_serialize, current_depth)
return object_to_serialize if natively_embeddable?(object_to_serialize)
return object_to_serialize.export if object_to_serialize.is_a? LightMongo::Document and current_depth > 0
return hashify(object_to_serialize, current_depth)
end
def hashify(object_to_serialize, current_depth)
hashed_object = {}
hashed_object['_class_name'] = object_to_serialize.class.name if current_depth > 0
object_to_serialize.instance_variables.each do |attribute_name|
new_hash_key = attribute_name.to_s.sub(/^@/, '')
nested_object = object_to_serialize.instance_variable_get(attribute_name)
hashed_object[new_hash_key] = Serializer.serialize(nested_object, current_depth + 1)
end
return hashed_object
end
def natively_embeddable?(object)
begin
raise_unless_natively_embeddable(object)
rescue Mongo::InvalidDocument => e
return false
end
return true
end
def raise_unless_natively_embeddable(object)
BSON_RUBY.new.bson_type(object)
end
end
end
end
end
end