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

#dot_delete(k) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/mongoo/mongohash.rb', line 44

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



33
34
35
36
37
38
39
40
41
42
# File 'lib/mongoo/mongohash.rb', line 33

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



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/mongoo/mongohash.rb', line 59

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



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/mongoo/mongohash.rb', line 18

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



71
72
73
# File 'lib/mongoo/mongohash.rb', line 71

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