Mercurial > repos > other > Puppet
comparison modules/php/lib/puppet/parser/functions/ensure_prefix.rb @ 386:3fce34f642f1
Add a PHP module to handle platform differences
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Mon, 03 Jan 2022 17:09:39 +0000 |
parents | |
children | adf6fe9bbc17 |
comparison
equal
deleted
inserted
replaced
385:d9009f54eb23 | 386:3fce34f642f1 |
---|---|
1 | |
2 module Puppet::Parser::Functions | |
3 newfunction(:ensure_prefix, type: :rvalue, doc: <<-EOS | |
4 This function ensures a prefix for all elements in an array or the keys in a hash. | |
5 | |
6 *Examples:* | |
7 | |
8 ensure_prefix({'a' => 1, 'b' => 2, 'p.c' => 3}, 'p.') | |
9 | |
10 Will return: | |
11 { | |
12 'p.a' => 1, | |
13 'p.b' => 2, | |
14 'p.c' => 3, | |
15 } | |
16 | |
17 ensure_prefix(['a', 'p.b', 'c'], 'p.') | |
18 | |
19 Will return: | |
20 ['p.a', 'p.b', 'p.c'] | |
21 EOS | |
22 ) do |arguments| | |
23 if arguments.size < 2 | |
24 raise(Puppet::ParseError, 'ensure_prefix(): Wrong number of arguments ' \ | |
25 "given (#{arguments.size} for 2)") | |
26 end | |
27 | |
28 enumerable = arguments[0] | |
29 | |
30 unless enumerable.is_a?(Array) || enumerable.is_a?(Hash) | |
31 raise Puppet::ParseError, "ensure_prefix(): expected first argument to be an Array or a Hash, got #{enumerable.inspect}" | |
32 end | |
33 | |
34 prefix = arguments[1] if arguments[1] | |
35 | |
36 if prefix | |
37 unless prefix.is_a?(String) | |
38 raise Puppet::ParseError, "ensure_prefix(): expected second argument to be a String, got #{prefix.inspect}" | |
39 end | |
40 end | |
41 | |
42 result = if enumerable.is_a?(Array) | |
43 # Turn everything into string same as join would do ... | |
44 enumerable.map do |i| | |
45 i = i.to_s | |
46 prefix && !i.start_with?(prefix) ? prefix + i : i | |
47 end | |
48 else | |
49 Hash[enumerable.map do |k, v| | |
50 k = k.to_s | |
51 [prefix && !k.start_with?(prefix) ? prefix + k : k, v] | |
52 end] | |
53 end | |
54 | |
55 return result | |
56 end | |
57 end |