Class: Mongoo::Mongohash

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/mongoo/mongohash.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ Mongohash

Returns a new instance of Mongohash.



13
14
15
16
# File 'lib/mongoo/mongohash.rb', line 13

def initialize(hash={})
  hash = hash.to_hash unless hash.class.to_s == "Hash"
  @raw_hash = hash.deep_stringify_keys
end

Instance Attribute Details

#raw_hashObject (readonly)

Returns the value of attribute raw_hash.



11
12
13
# File 'lib/mongoo/mongohash.rb', line 11

def raw_hash
  @raw_hash
end

Instance Method Details

#deep_cloneObject



18
19
20
# File 'lib/mongoo/mongohash.rb', line 18

def deep_clone
  Mongoo::Mongohash.new(Marshal.load(Marshal.dump self.raw_hash))
end

#dot_delete(k) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/mongoo/mongohash.rb', line 48

def dot_delete(k)
  parts    = k.to_s.split(".")
  curr_val = to_hash
  while !parts.empty?
    part = parts.shift
    if parts.empty?
      curr_val.delete(part)
      return true
    else
      curr_val = curr_val[part]
    end
  end
  false
end

#dot_get(k) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# File 'lib/mongoo/mongohash.rb', line 37

def dot_get(k)
  parts    = k.to_s.split(".")
  curr_val = to_hash
  while !parts.empty?
    part = parts.shift
    curr_val = curr_val[part]
    return curr_val unless curr_val.is_a?(Hash)
  end
  curr_val
end

#dot_list(curr_hash = self.to_hash, path = []) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mongoo/mongohash.rb', line 63

def dot_list(curr_hash=self.to_hash, path=[])
  list = []
  curr_hash.each do |k,v|
    if v.is_a?(Hash)
      list.concat dot_list(v, (path + [k]))
    else
      list << (path + [k]).join(".")
    end
  end
  list
end

#dot_set(k, v) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/mongoo/mongohash.rb', line 22

def dot_set(k,v)
  parts    = k.to_s.split(".")
  curr_val = to_hash
  while !parts.empty?
    part = parts.shift
    if parts.empty?
      curr_val[part] = v
    else
      curr_val[part] ||= {}
      curr_val = curr_val[part]
    end
  end
  true
end

#to_key_valueObject



75
76
77
# File 'lib/mongoo/mongohash.rb', line 75

def to_key_value
  kv = {}; dot_list.collect { |k| kv[k] = dot_get(k) }; kv
end