Module: Sergio::HashMethods

Included in:
Config, ParsedDocument
Defined in:
lib/sergio/hash_methods.rb

Instance Method Summary collapse

Instance Method Details

#hash_from_path(path, val) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
# File 'lib/sergio/hash_methods.rb', line 3

def hash_from_path(path, val)
  path = path.clone
  k = path.shift
  h = {}
  h[k] = if path.empty?
    val
  else
    hash_from_path(path, val)
  end
  h
end

#hash_recursive_append(lval, rval) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/sergio/hash_methods.rb', line 53

def hash_recursive_append(lval, rval)
  r = {}
  v = lval.merge(rval) do |key, oldval, newval|
    r[key] = if oldval.is_a?(Hash) && newval.is_a?(Hash)
      if newval.size == 0
        [oldval, newval]
      else
        hash_recursive_append(oldval, newval)
      end
    else
      if oldval.is_a?(Array)
        if oldval.last.is_a?(Hash) && newval.is_a?(Hash) && newval.size > 0
          oldval << hash_recursive_append(oldval.pop, newval)
        else
          oldval << newval
        end
      elsif newval.is_a?(Array)
        newval << oldval
      else
        [oldval] << newval
      end
    end
  end
  v
end

#hash_recursive_merge_to_arrays(lval, rval) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/sergio/hash_methods.rb', line 34

def hash_recursive_merge_to_arrays(lval, rval)
  r = {}
  v = lval.merge(rval) do |key, oldval, newval| 
    v = if oldval.class == lval.class
      hash_recursive_merge_to_arrays(oldval, newval) 
    else
      if oldval.is_a?(Array)
        oldval << newval
      elsif newval.is_a?(Array)
        newval << oldval
      else
        [oldval] << newval
      end
    end
    r[key] = v
  end
  v
end

#value_at_path(path, hash) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/sergio/hash_methods.rb', line 15

def value_at_path(path, hash)
  k = path.shift
  k = k.is_a?(Array) ? k[0] : k
  v = hash[k]
  if v
    if path.length > 0
      if v.is_a?(Hash)
        value_at_path(path, v)
      elsif v.last.is_a?(Hash)
        value_at_path(path, v.last)
      end
    else
      v
    end
  else
    nil
  end
end