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.
10 prefix(['a','b','c'], 'p')
12 Will return: ['pa','pb','pc']
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:
17 ['a', 'b', 'c'].map |$x| { "p${x}" }
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?
24 enumerable = arguments[0]
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}"
30 prefix = arguments[1] if arguments[1]
33 unless prefix.is_a?(String)
34 raise Puppet::ParseError, "prefix(): expected second argument to be a String, got #{prefix.inspect}"
38 result = if enumerable.is_a?(Array)
39 # Turn everything into string same as join would do ...
42 prefix ? prefix + i : i
45 Hash[enumerable.map do |k, v|
47 [prefix ? prefix + k : k, v]
55 # vim: set ts=2 sw=2 et :