Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / any2array.rb
1 #
2 # any2array.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:any2array, :type => :rvalue, :doc => <<-DOC
6     @summary
7       This converts any object to an array containing that object.
8
9     Empty argument lists are converted to an empty array. Arrays are left
10     untouched. Hashes are converted to arrays of alternating keys and values.
11
12     > *Note:*
13       since Puppet 5.0.0 it is possible to create new data types for almost any
14       datatype using the type system and the built-in
15       [`Array.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-array-and-tuple)
16       function is used to create a new Array..
17
18       ```
19       $hsh = {'key' => 42, 'another-key' => 100}
20       notice(Array($hsh))
21       ```
22
23     Would notice `[['key', 42], ['another-key', 100]]`
24
25     The Array data type also has a special mode to "create an array if not already an array"
26
27       ```
28       notice(Array({'key' => 42, 'another-key' => 100}, true))
29       ```
30
31     Would notice `[{'key' => 42, 'another-key' => 100}]`, as the `true` flag prevents the hash from being
32     transformed into an array.
33
34     @return [Array] The new array containing the given object
35   DOC
36              ) do |arguments|
37
38     if arguments.empty?
39       return []
40     end
41
42     return arguments unless arguments.length == 1
43     return arguments[0] if arguments[0].is_a?(Array)
44     return [] if arguments == ['']
45     if arguments[0].is_a?(Hash)
46       result = []
47       arguments[0].each do |key, value|
48         result << key << value
49       end
50       return result
51     end
52     return arguments
53   end
54 end
55
56 # vim: set ts=2 sw=2 et :