]> git.donarmstrong.com Git - dsa-puppet.git/blob - modules/stdlib/lib/puppet/parser/functions/zip.rb
upgrade to concat 2.0.0
[dsa-puppet.git] / modules / stdlib / lib / puppet / parser / functions / zip.rb
1 #
2 # zip.rb
3 #
4
5 module Puppet::Parser::Functions
6   newfunction(:zip, :type => :rvalue, :doc => <<-EOS
7 Takes one element from first array and merges corresponding elements from second array. This generates a sequence of n-element arrays, where n is one more than the count of arguments.
8
9 *Example:*
10
11     zip(['1','2','3'],['4','5','6'])
12
13 Would result in:
14
15     ["1", "4"], ["2", "5"], ["3", "6"]
16     EOS
17   ) do |arguments|
18
19     # Technically we support three arguments but only first is mandatory ...
20     raise(Puppet::ParseError, "zip(): Wrong number of arguments " +
21       "given (#{arguments.size} for 2)") if arguments.size < 2
22
23     a = arguments[0]
24     b = arguments[1]
25
26     unless a.is_a?(Array) and b.is_a?(Array)
27       raise(Puppet::ParseError, 'zip(): Requires array to work with')
28     end
29
30     flatten = arguments[2] if arguments[2]
31
32     if flatten
33       klass = flatten.class
34
35       # We can have either true or false, or string which resembles boolean ...
36       unless [FalseClass, TrueClass, String].include?(klass)
37         raise(Puppet::ParseError, 'zip(): Requires either ' +
38           'boolean or string to work with')
39       end
40
41       if flatten.is_a?(String)
42         # We consider all the yes, no, y, n and so on too ...
43         flatten = case flatten
44           #
45           # This is how undef looks like in Puppet ...
46           # We yield false in this case.
47           #
48           when /^$/, '' then false # Empty string will be false ...
49           when /^(1|t|y|true|yes)$/  then true
50           when /^(0|f|n|false|no)$/  then false
51           when /^(undef|undefined)$/ then false # This is not likely to happen ...
52           else
53             raise(Puppet::ParseError, 'zip(): Unknown type of boolean given')
54         end
55       end
56     end
57
58     result = a.zip(b)
59     result = flatten ? result.flatten : result
60
61     return result
62   end
63 end
64
65 # vim: set ts=2 sw=2 et :