1 | #
|
---|
2 | # dig44.rb
|
---|
3 | #
|
---|
4 |
|
---|
5 | module Puppet::Parser::Functions
|
---|
6 | newfunction(
|
---|
7 | :dig44,
|
---|
8 | :type => :rvalue,
|
---|
9 | :arity => -2,
|
---|
10 | :doc => <<-eos
|
---|
11 | DEPRECATED: This function has been replaced in puppet 4.5.0.
|
---|
12 |
|
---|
13 | Looks up into a complex structure of arrays and hashes and returns a value
|
---|
14 | or the default value if nothing was found.
|
---|
15 |
|
---|
16 | Key can contain slashes to describe path components. The function will go down
|
---|
17 | the structure and try to extract the required value.
|
---|
18 |
|
---|
19 | $data = {
|
---|
20 | 'a' => {
|
---|
21 | 'b' => [
|
---|
22 | 'b1',
|
---|
23 | 'b2',
|
---|
24 | 'b3',
|
---|
25 | ]
|
---|
26 | }
|
---|
27 | }
|
---|
28 |
|
---|
29 | $value = dig44($data, ['a', 'b', '2'], 'not_found')
|
---|
30 | => $value = 'b3'
|
---|
31 |
|
---|
32 | a -> first hash key
|
---|
33 | b -> second hash key
|
---|
34 | 2 -> array index starting with 0
|
---|
35 |
|
---|
36 | not_found -> (optional) will be returned if there is no value or the path
|
---|
37 | did not match. Defaults to nil.
|
---|
38 |
|
---|
39 | In addition to the required "key" argument, the function accepts a default
|
---|
40 | argument. It will be returned if no value was found or a path component is
|
---|
41 | missing. And the fourth argument can set a variable path separator.
|
---|
42 | eos
|
---|
43 | ) do |arguments|
|
---|
44 | # Two arguments are required
|
---|
45 | raise(Puppet::ParseError, "dig44(): Wrong number of arguments " +
|
---|
46 | "given (#{arguments.size} for at least 2)") if arguments.size < 2
|
---|
47 |
|
---|
48 | data, path, default = *arguments
|
---|
49 |
|
---|
50 | unless data.is_a?(Hash) or data.is_a?(Array)
|
---|
51 | raise(Puppet::ParseError, "dig44(): first argument must be a hash or an array, " <<
|
---|
52 | "given #{data.class.name}")
|
---|
53 | end
|
---|
54 |
|
---|
55 | unless path.is_a? Array
|
---|
56 | raise(Puppet::ParseError, "dig44(): second argument must be an array, " <<
|
---|
57 | "given #{path.class.name}")
|
---|
58 | end
|
---|
59 |
|
---|
60 | value = path.reduce(data) do |structure, key|
|
---|
61 | if structure.is_a? Hash or structure.is_a? Array
|
---|
62 | if structure.is_a? Array
|
---|
63 | key = Integer key rescue break
|
---|
64 | end
|
---|
65 | break if structure[key].nil? or structure[key] == :undef
|
---|
66 | structure[key]
|
---|
67 | else
|
---|
68 | break
|
---|
69 | end
|
---|
70 | end
|
---|
71 | value.nil? ? default : value
|
---|
72 | end
|
---|
73 | end
|
---|