File: any2array.rb

package info (click to toggle)
puppet-module-puppetlabs-stdlib 9.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,448 kB
  • sloc: ruby: 3,522; sh: 46; makefile: 2
file content (56 lines) | stat: -rw-r--r-- 1,615 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# frozen_string_literal: true

#
# any2array.rb
#
module Puppet::Parser::Functions
  newfunction(:any2array, type: :rvalue, doc: <<-DOC
    @summary
      This converts any object to an array containing that object.

    Empty argument lists are converted to an empty array. Arrays are left
    untouched. Hashes are converted to arrays of alternating keys and values.

    > *Note:*
      since Puppet 5.0.0 it is possible to create new data types for almost any
      datatype using the type system and the built-in
      [`Array.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-array-and-tuple)
      function is used to create a new Array..

      ```
      $hsh = {'key' => 42, 'another-key' => 100}
      notice(Array($hsh))
      ```

    Would notice `[['key', 42], ['another-key', 100]]`

    The Array data type also has a special mode to "create an array if not already an array"

      ```
      notice(Array({'key' => 42, 'another-key' => 100}, true))
      ```

    Would notice `[{'key' => 42, 'another-key' => 100}]`, as the `true` flag prevents the hash from being
    transformed into an array.

    @return [Array] The new array containing the given object
  DOC
  ) do |arguments|
    return [] if arguments.empty?

    return arguments unless arguments.length == 1
    return arguments[0] if arguments[0].is_a?(Array)
    return [] if arguments == ['']

    if arguments[0].is_a?(Hash)
      result = []
      arguments[0].each do |key, value|
        result << key << value
      end
      return result
    end
    return arguments
  end
end

# vim: set ts=2 sw=2 et :