Module: TinyMongo::Helper

Defined in:
lib/tinymongo/helper.rb

Class Method Summary collapse

Class Method Details

.bson_object_id(id) ⇒ Object



76
77
78
79
80
81
82
83
84
# File 'lib/tinymongo/helper.rb', line 76

def bson_object_id(id)
  if(id.instance_of? BSON::ObjectID)
    id
  elsif(id.instance_of? String)
    BSON::ObjectID(id)
  else
    BSON::ObjectID(id.to_s)
  end
end

.constantize(class_name) ⇒ Object



4
5
6
7
# File 'lib/tinymongo/helper.rb', line 4

def constantize(class_name)
  return unless class_name.instance_of? String
  class_name.split('::').inject(Object) { |mod, klass| mod.const_get(klass) }
end

.deep_copy(obj) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/tinymongo/helper.rb', line 9

def deep_copy(obj)
  if(obj.kind_of? Hash)
    Hash[obj.map { |k,v| [k.to_s, deep_copy(v)] }]
  elsif(obj.kind_of? Array)
    obj.map { |o| deep_copy(o)}
  else
    begin
      obj.dup
    rescue
      obj
    end
  end
end

.deserialize_hashes_in(obj) ⇒ Object



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
# File 'lib/tinymongo/helper.rb', line 35

def deserialize_hashes_in(obj)
  if(obj.kind_of? Hash)
    new_hash = Hash[obj.map { |k,v| [k.to_s, deserialize_hashes_in(v)] }]
    class_name = new_hash['_tinymongo_model_class_name']
    if(class_name)
      begin
        klass = constantize(new_hash['_tinymongo_model_class_name'])
        if(klass.new.kind_of? TinyMongo::Model)
          deserialized_obj = klass.new(new_hash)
        else
          raise
        end
      rescue
        raise DeserializationError, class_name
      end
      deserialized_obj
    else
      new_hash
    end
  elsif(obj.kind_of? Array)
    obj.map { |o| deserialize_hashes_in(o) }
  else
    obj
  end
end

.hashify_models_in(obj) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/tinymongo/helper.rb', line 61

def hashify_models_in(obj)
  if(obj.kind_of? Hash)
    Hash[obj.map do |k,v| 
      key = k.to_s
      (key == '_id') ? [key, bson_object_id(v)] : [key, hashify_models_in(v)]
    end]
  elsif(obj.kind_of? Array)
    obj.map { |o| hashify_models_in(o) }
  elsif(obj.kind_of? TinyMongo::Model)
    hashify_models_in(obj.to_hash)
  else
    obj
  end
end

.stringify_keys_in_hash(hash) ⇒ Object



23
24
25
26
27
# File 'lib/tinymongo/helper.rb', line 23

def stringify_keys_in_hash(hash)
  new_hash = Hash[hash.map { |k,v| [k.to_s, v] }]
  new_hash['_id'] = bson_object_id(new_hash['_id']) if(new_hash['_id'])
  new_hash
end

.symbolify_keys_in_hash(hash) ⇒ Object



29
30
31
32
33
# File 'lib/tinymongo/helper.rb', line 29

def symbolify_keys_in_hash(hash)
  new_hash = Hash[hash.map { |k,v| [k.to_sym, v] }]
  new_hash[:_id] = bson_object_id(new_hash[:_id]) if(new_hash[:_id])
  new_hash
end