Update puppetlabs/stdlib module
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / any2bool.rb
1 #
2 # any2bool.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:any2bool, :type => :rvalue, :doc => <<-DOC
6     This converts 'anything' to a boolean. In practise it does the following:
7
8     * Strings such as Y,y,1,T,t,TRUE,yes,'true' will return true
9     * Strings such as 0,F,f,N,n,FALSE,no,'false' will return false
10     * Booleans will just return their original value
11     * Number (or a string representation of a number) > 0 will return true, otherwise false
12     * undef will return false
13     * Anything else will return true
14
15     Also see the built-in [`Boolean.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-boolean)
16     function.
17   DOC
18              ) do |arguments|
19
20     raise(Puppet::ParseError, "any2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty?
21
22     # If argument is already Boolean, return it
23     if !!arguments[0] == arguments[0] # rubocop:disable Style/DoubleNegation : Could not find a better way to check if a boolean
24       return arguments[0]
25     end
26
27     arg = arguments[0]
28
29     if arg.nil?
30       return false
31     end
32
33     if arg == :undef
34       return false
35     end
36
37     valid_float = begin
38                     !!Float(arg) # rubocop:disable Style/DoubleNegation : Could not find a better way to check if a boolean
39                   rescue
40                     false
41                   end
42
43     if arg.is_a?(Numeric)
44       return function_num2bool([arguments[0]])
45     end
46
47     if arg.is_a?(String)
48       return function_num2bool([arguments[0]]) if valid_float
49       return function_str2bool([arguments[0]])
50     end
51
52     return true
53   end
54 end
55
56 # vim: set ts=2 sw=2 et :