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