summaryrefslogtreecommitdiff
path: root/lib/puppet/parser/functions/dig44.rb
diff options
context:
space:
mode:
authorvarac <varacanero@zeromail.org>2017-01-13 12:41:58 +0100
committervarac <varacanero@zeromail.org>2017-01-13 12:41:58 +0100
commit066c08f8362d53f0f30897cb8710d11260c726ea (patch)
treea6369eecd88bb731fe413d0bbc8af73d74d1f447 /lib/puppet/parser/functions/dig44.rb
parent71123634744b9fe2ec7d6a3e38e9789fd84801e3 (diff)
parentb65dd1f45d10e10e45455358aeabb29167990e2c (diff)
Merge remote-tracking branch 'origin/master' into leap_master
Diffstat (limited to 'lib/puppet/parser/functions/dig44.rb')
-rw-r--r--lib/puppet/parser/functions/dig44.rb73
1 files changed, 73 insertions, 0 deletions
diff --git a/lib/puppet/parser/functions/dig44.rb b/lib/puppet/parser/functions/dig44.rb
new file mode 100644
index 0000000..1e7c318
--- /dev/null
+++ b/lib/puppet/parser/functions/dig44.rb
@@ -0,0 +1,73 @@
+#
+# dig44.rb
+#
+
+module Puppet::Parser::Functions
+ newfunction(
+ :dig44,
+ :type => :rvalue,
+ :arity => -2,
+ :doc => <<-eos
+DEPRECATED: This function has been replaced in puppet 4.5.0.
+
+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 = dig44($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.
+
+In addition to the required "key" argument, the function accepts a 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.
+ eos
+ ) do |arguments|
+ # Two arguments are required
+ raise(Puppet::ParseError, "dig44(): Wrong number of arguments " +
+ "given (#{arguments.size} for at least 2)") if arguments.size < 2
+
+ data, path, default = *arguments
+
+ unless data.is_a?(Hash) or data.is_a?(Array)
+ raise(Puppet::ParseError, "dig44(): first argument must be a hash or an array, " <<
+ "given #{data.class.name}")
+ end
+
+ unless path.is_a? Array
+ raise(Puppet::ParseError, "dig44(): second argument must be an array, " <<
+ "given #{path.class.name}")
+ end
+
+ value = path.reduce(data) do |structure, key|
+ if structure.is_a? Hash or structure.is_a? Array
+ if structure.is_a? Array
+ key = Integer key rescue break
+ end
+ break if structure[key].nil? or structure[key] == :undef
+ structure[key]
+ else
+ break
+ end
+ end
+ value.nil? ? default : value
+ end
+end