Suggest different variables to use if we want to tunnel both v4 and v6
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / join_keys_to_values.rb
1 #
2 # join_keys_to_values.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:join_keys_to_values, :type => :rvalue, :doc => <<-DOC
6     This function joins each key of a hash to that key's corresponding value with a
7     separator. Keys are cast to strings. If values are arrays, multiple keys
8     are added for each element. The return value is an array in
9     which each element is one joined key/value pair.
10
11     *Examples:*
12
13         join_keys_to_values({'a'=>1,'b'=>2}, " is ")
14
15     Would result in: ["a is 1","b is 2"]
16
17         join_keys_to_values({'a'=>1,'b'=>[2,3]}, " is ")
18
19     Would result in: ["a is 1","b is 2","b is 3"]
20
21     Note: Since Puppet 5.0.0 - for more detailed control over the formatting (including indentations and
22     line breaks, delimiters around arrays and hash entries, between key/values in hash entries, and individual
23     formatting of values in the array) - see the `new` function for `String` and its formatting
24     options for `Array` and `Hash`.
25     DOC
26              ) do |arguments|
27
28     # Validate the number of arguments.
29     if arguments.size != 2
30       raise(Puppet::ParseError, "join_keys_to_values(): Takes exactly two arguments, but #{arguments.size} given.")
31     end
32
33     # Validate the first argument.
34     hash = arguments[0]
35     unless hash.is_a?(Hash)
36       raise(TypeError, "join_keys_to_values(): The first argument must be a hash, but a #{hash.class} was given.")
37     end
38
39     # Validate the second argument.
40     separator = arguments[1]
41     unless separator.is_a?(String)
42       raise(TypeError, "join_keys_to_values(): The second argument must be a string, but a #{separator.class} was given.")
43     end
44
45     # Join the keys to their values.
46     hash.map { |k, v|
47       if v.is_a?(Array)
48         v.map { |va| String(k) + separator + String(va) }
49       elsif String(v) == 'undef'
50         String(k)
51       else
52         String(k) + separator + String(v)
53       end
54     }.flatten
55   end
56 end
57
58 # vim: set ts=2 sw=2 et :