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 / prefix.rb
1 #
2 # prefix.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:prefix, :type => :rvalue, :doc => <<-DOC
6     This function applies a prefix to all elements in an array or a hash.
7
8     *Examples:*
9
10         prefix(['a','b','c'], 'p')
11
12     Will return: ['pa','pb','pc']
13
14     Note that since Puppet 4.0.0 the general way to modify values is in array is by using the map
15     function in Puppet. This example does the same as the example above:
16
17         ['a', 'b', 'c'].map |$x| { "p${x}" }
18     DOC
19              ) do |arguments|
20
21     # Technically we support two arguments but only first is mandatory ...
22     raise(Puppet::ParseError, "prefix(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty?
23
24     enumerable = arguments[0]
25
26     unless enumerable.is_a?(Array) || enumerable.is_a?(Hash)
27       raise Puppet::ParseError, "prefix(): expected first argument to be an Array or a Hash, got #{enumerable.inspect}"
28     end
29
30     prefix = arguments[1] if arguments[1]
31
32     if prefix
33       unless prefix.is_a?(String)
34         raise Puppet::ParseError, "prefix(): expected second argument to be a String, got #{prefix.inspect}"
35       end
36     end
37
38     result = if enumerable.is_a?(Array)
39                # Turn everything into string same as join would do ...
40                enumerable.map do |i|
41                  i = i.to_s
42                  prefix ? prefix + i : i
43                end
44              else
45                Hash[enumerable.map do |k, v|
46                  k = k.to_s
47                  [prefix ? prefix + k : k, v]
48                end]
49              end
50
51     return result
52   end
53 end
54
55 # vim: set ts=2 sw=2 et :