Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/cucumber/helpers/core_ext.rb

Instance Method Summary collapse

Instance Method Details

#deep_delete(deep_key) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/cucumber/helpers/core_ext.rb', line 16

def deep_delete(deep_key)
  path_keys = deep_key.split('.')
  final_key = path_keys.pop

  sub_obj = self
  path_keys.each do |k|
    if k.match(/^(.+)\[(\d+)\]$/)
      sub_obj = sub_obj[$1][$2.to_i]
    else
      sub_obj = sub_obj[k]
    end
  end

  sub_obj.delete(final_key)
end

#deep_key(deep_key) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/cucumber/helpers/core_ext.rb', line 2

def deep_key(deep_key)
  sub_obj = self
  deep_key.split('.').each do |k|
    if k.match(/^(.+)\[(\d+)\]$/)
      sub_obj = sub_obj[$1][$2.to_i]
    else
      sub_obj = sub_obj[k]
    end
  end
  sub_obj
rescue
  nil
end

#deep_set(deep_key, value) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/cucumber/helpers/core_ext.rb', line 32

def deep_set(deep_key, value)
  path_keys = deep_key.split('.')
  final_key = path_keys.pop

  sub_obj = self
  path_keys.each do |k|
    if k.match(/^(.+)\[(\d+)\]$/)
      sub_obj = sub_obj[$1][$2.to_i]
    else
      sub_obj[k] ||= {}
      sub_obj = sub_obj[k]
    end
  end

  if final_key.match(/^(.+)\[(\d+)\]$/)
    sub_obj[$1][$2.to_i] = value
  else 
    sub_obj[final_key] = value
  end
end

#flat_hash(separator = ".") ⇒ Object

Collapses any nested hashes, converting the keys to delimited strings.

For example, the hash ‘{ “address” => { “line1” => …, “line2” => … } }` will be converted to `{ “address.line1” => …, “address.line2” => … }`. The keys produced are compatible with the `deep_*` functions on hash, so this can provide a convenient way to iterate through values of a hash.

Note that this function is lossy - if two nested hashes would result in the same keys then only one will be preserved.



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/cucumber/helpers/core_ext.rb', line 62

def flat_hash(separator = ".")
  each_with_object({}) do |(k, v), result|
    if v.is_a?(Hash)
      v.flat_hash(separator).each do |k2, v2|
        result["#{k}#{separator}#{k2}"] = v2
      end
    else
      result[k] = v
    end
  end
end