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