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 and values are cast to strings. 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 | EOS
|
---|
17 | ) do |arguments|
|
---|
18 |
|
---|
19 | # Validate the number of arguments.
|
---|
20 | if arguments.size != 2
|
---|
21 | raise(Puppet::ParseError, "join_keys_to_values(): Takes exactly two " +
|
---|
22 | "arguments, but #{arguments.size} given.")
|
---|
23 | end
|
---|
24 |
|
---|
25 | # Validate the first argument.
|
---|
26 | hash = arguments[0]
|
---|
27 | if not hash.is_a?(Hash)
|
---|
28 | raise(TypeError, "join_keys_to_values(): The first argument must be a " +
|
---|
29 | "hash, but a #{hash.class} was given.")
|
---|
30 | end
|
---|
31 |
|
---|
32 | # Validate the second argument.
|
---|
33 | separator = arguments[1]
|
---|
34 | if not separator.is_a?(String)
|
---|
35 | raise(TypeError, "join_keys_to_values(): The second argument must be a " +
|
---|
36 | "string, but a #{separator.class} was given.")
|
---|
37 | end
|
---|
38 |
|
---|
39 | # Join the keys to their values.
|
---|
40 | hash.map do |k,v|
|
---|
41 | String(k) + separator + String(v)
|
---|
42 | end
|
---|
43 |
|
---|
44 | end
|
---|
45 | end
|
---|
46 |
|
---|
47 | # vim: set ts=2 sw=2 et :
|
---|