Update stdlib and concat to 6.1.0 both
[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     @summary
7       This function applies a prefix to all elements in an array or a hash.
8
9     @example **Usage**
10
11       prefix(['a','b','c'], 'p')
12       Will return: ['pa','pb','pc']
13
14     > *Note:* 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     ['a', 'b', 'c'].map |$x| { "p${x}" }
17
18     @return [Hash] or [Array] The passed values now contains the passed prefix
19     DOC
20              ) do |arguments|
21
22     # Technically we support two arguments but only first is mandatory ...
23     raise(Puppet::ParseError, "prefix(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty?
24
25     enumerable = arguments[0]
26
27     unless enumerable.is_a?(Array) || enumerable.is_a?(Hash)
28       raise Puppet::ParseError, "prefix(): expected first argument to be an Array or a Hash, got #{enumerable.inspect}"
29     end
30
31     prefix = arguments[1] if arguments[1]
32
33     if prefix
34       unless prefix.is_a?(String)
35         raise Puppet::ParseError, "prefix(): expected second argument to be a String, got #{prefix.inspect}"
36       end
37     end
38
39     result = if enumerable.is_a?(Array)
40                # Turn everything into string same as join would do ...
41                enumerable.map do |i|
42                  i = i.to_s
43                  prefix ? prefix + i : i
44                end
45              else
46                Hash[enumerable.map do |k, v|
47                  k = k.to_s
48                  [prefix ? prefix + k : k, v]
49                end]
50              end
51
52     return result
53   end
54 end
55
56 # vim: set ts=2 sw=2 et :