Puppet Function: try_get_value

Defined in:
vendor_modules/stdlib/lib/puppet/parser/functions/try_get_value.rb
Function type:
Ruby 3.x API

Summary

**DEPRECATED:** this function is deprecated, please use dig() instead.

Overview

try_get_value()Any

Key can contain slashes to describe path components. The function will go down the structure and try to extract the required value. “ $data = {

'a' => {
  'b' => [
    'b1',
    'b2',
    'b3',
  ]
}

}

$value = try_get_value($data, 'a/b/2', 'not_found', '/')

> $value = 'b3'

“` “` a -> first hash key b -> second hash key 2 -> array index starting with 0

not_found -> (optional) will be returned if there is no value or the path did not match. Defaults to nil. / -> (optional) path delimiter. Defaults to '/'. “`

In addition to the required “key” argument, “try_get_value” accepts default argument. It will be returned if no value was found or a path component is missing. And the fourth argument can set a variable path separator.

Returns:

  • (Any)

    Looks up into a complex structure of arrays and hashes and returns a value or the default value if nothing was found.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'vendor_modules/stdlib/lib/puppet/parser/functions/try_get_value.rb', line 7

newfunction(:try_get_value, type: :rvalue, arity: -2, doc: <<-DOC
    @summary
      **DEPRECATED:** this function is deprecated, please use dig() instead.

    @return
      Looks up into a complex structure of arrays and hashes and returns a value
      or the default value if nothing was found.

    Key can contain slashes to describe path components. The function will go down
    the structure and try to extract the required value.
    ``
    $data = {
      'a' => {
        'b' => [
          'b1',
          'b2',
          'b3',
        ]
      }
    }

    $value = try_get_value($data, 'a/b/2', 'not_found', '/')
    => $value = 'b3'
    ```
    ```
    a -> first hash key
    b -> second hash key
    2 -> array index starting with 0

    not_found -> (optional) will be returned if there is no value or the path did not match. Defaults to nil.
    / -> (optional) path delimiter. Defaults to '/'.
    ```

    In addition to the required "key" argument, "try_get_value" accepts default
    argument. It will be returned if no value was found or a path component is
    missing. And the fourth argument can set a variable path separator.
  DOC
) do |args|
  warning('try_get_value() DEPRECATED: this function is deprecated, please use dig() instead.')
  data = args[0]
  path = args[1] || ''
  default = args[2]

  if !(data.is_a?(Hash) || data.is_a?(Array)) || path == ''
    return default || data
  end

  separator = args[3] || '/'
  path = path.split(separator).map { |key| (key =~ %r{^\d+$}) ? key.to_i : key }
  function_dig([data, path, default])
end