Update stdlib
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / try_get_value.rb
1 module Puppet::Parser::Functions
2   newfunction(
3       :try_get_value,
4       :type => :rvalue,
5       :arity => -2,
6       :doc => <<-eos
7 DEPRECATED: this function is deprecated, please use dig() instead.
8
9 Looks up into a complex structure of arrays and hashes and returns a value
10 or the default value if nothing was found.
11
12 Key can contain slashes to describe path components. The function will go down
13 the structure and try to extract the required value.
14
15 $data = {
16   'a' => {
17     'b' => [
18       'b1',
19       'b2',
20       'b3',
21     ]
22   }
23 }
24
25 $value = try_get_value($data, 'a/b/2', 'not_found', '/')
26 => $value = 'b3'
27
28 a -> first hash key
29 b -> second hash key
30 2 -> array index starting with 0
31
32 not_found -> (optional) will be returned if there is no value or the path did not match. Defaults to nil.
33 / -> (optional) path delimiter. Defaults to '/'.
34
35 In addition to the required "key" argument, "try_get_value" accepts default
36 argument. It will be returned if no value was found or a path component is
37 missing. And the fourth argument can set a variable path separator.
38   eos
39   ) do |args|
40     warning("try_get_value() DEPRECATED: this function is deprecated, please use dig() instead.")
41     data = args[0]
42     path = args[1] || ''
43     default = args[2]
44
45     if !(data.is_a?(Hash) || data.is_a?(Array)) || path == ''
46       return default || data
47     end
48
49     separator = args[3] || '/'
50     path = path.split(separator).map{ |key| key =~ /^\d+$/ ? key.to_i : key }
51     function_dig([data, path, default])
52   end
53 end