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