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