Update stdlib
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / join_keys_to_values.rb
1 #
2 # join.rb
3 #
4
5 module Puppet::Parser::Functions
6   newfunction(:join_keys_to_values, :type => :rvalue, :doc => <<-EOS
7 This function joins each key of a hash to that key's corresponding value with a
8 separator. Keys are cast to strings. If values are arrays, multiple keys
9 are added for each element. The return value is an array in
10 which each element is one joined key/value pair.
11
12 *Examples:*
13
14     join_keys_to_values({'a'=>1,'b'=>2}, " is ")
15
16 Would result in: ["a is 1","b is 2"]
17
18     join_keys_to_values({'a'=>1,'b'=>[2,3]}, " is ")
19
20 Would result in: ["a is 1","b is 2","b is 3"]
21     EOS
22   ) do |arguments|
23
24     # Validate the number of arguments.
25     if arguments.size != 2
26       raise(Puppet::ParseError, "join_keys_to_values(): Takes exactly two arguments, but #{arguments.size} given.")
27     end
28
29     # Validate the first argument.
30     hash = arguments[0]
31     if not hash.is_a?(Hash)
32       raise(TypeError, "join_keys_to_values(): The first argument must be a hash, but a #{hash.class} was given.")
33     end
34
35     # Validate the second argument.
36     separator = arguments[1]
37     if not separator.is_a?(String)
38       raise(TypeError, "join_keys_to_values(): The second argument must be a string, but a #{separator.class} was given.")
39     end
40
41     # Join the keys to their values.
42     hash.map do |k,v|
43       if v.is_a?(Array)
44         v.map { |va| String(k) + separator + String(va) }
45       else
46         String(k) + separator + String(v)
47       end
48     end.flatten
49
50   end
51 end
52
53 # vim: set ts=2 sw=2 et :