Class: LightMongo::Document::Serialization::HashSerializer

Inherits:
Object
  • Object
show all
Defined in:
lib/document/serialization/hash_serializer.rb

Class Method Summary collapse

Class Method Details

.dump(object_to_serialize, current_depth = 0) ⇒ Object



9
10
11
12
13
14
15
16
17
18
# File 'lib/document/serialization/hash_serializer.rb', line 9

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

.hashify(object_to_serialize, current_depth) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/document/serialization/hash_serializer.rb', line 42

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.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

.natively_embeddable?(object) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
58
59
60
61
62
63
# File 'lib/document/serialization/hash_serializer.rb', line 55

def natively_embeddable?(object)
  begin
    raise_unless_natively_embeddable(object)
  rescue Mongo::InvalidDocument => e
    return false
  end
  
  return true
end

.raise_unless_natively_embeddable(object) ⇒ Object



65
66
67
# File 'lib/document/serialization/hash_serializer.rb', line 65

def raise_unless_natively_embeddable(object)
  BSON_RUBY.new.bson_type(object)
end

.serialize_array(object_to_serialize, current_depth) ⇒ Object



20
21
22
23
24
# File 'lib/document/serialization/hash_serializer.rb', line 20

def serialize_array(object_to_serialize, current_depth)
  object_to_serialize.map do |entry|
    Serializer.serialize(entry, current_depth + 1)
  end
end

.serialize_hash(object_to_serialize, current_depth) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/document/serialization/hash_serializer.rb', line 26

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

.serialize_object(object_to_serialize, current_depth) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/document/serialization/hash_serializer.rb', line 34

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