]> git.donarmstrong.com Git - dsa-puppet.git/blob - 3rdparty/modules/stdlib/lib/puppet/parser/functions/prefix.rb
upgrade to stdlib 4.6.1
[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 " +
19       "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, "prefix(): expected first argument to be an Array or a Hash, got #{enumerable.inspect}"
25     end
26
27     prefix = arguments[1] if arguments[1]
28
29     if prefix
30       unless prefix.is_a?(String)
31         raise Puppet::ParseError, "prefix(): expected second argument to be a String, got #{prefix.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         prefix ? prefix + i : i
40       end
41     else
42       result = Hash[enumerable.map do |k,v|
43         k = k.to_s
44         [ prefix ? prefix + k : k, v ]
45       end]
46     end
47
48     return result
49   end
50 end
51
52 # vim: set ts=2 sw=2 et :