Update stdlib and concat to 6.1.0 both
[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     @summary
7       This function joins each key of a hash to that key's corresponding value with a
8       separator.
9
10     Keys are cast to strings. If values are arrays, multiple keys
11     are added for each element. The return value is an array in
12     which each element is one joined key/value pair.
13
14     @example Example Usage:
15       join_keys_to_values({'a'=>1,'b'=>2}, " is ") # Results in: ["a is 1","b is 2"]
16       join_keys_to_values({'a'=>1,'b'=>[2,3]}, " is ") # Results in: ["a is 1","b is 2","b is 3"]
17
18     @return [Hash]
19       The joined hash
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 :