Update stdlib
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / str2bool.rb
1 #
2 # str2bool.rb
3 #
4
5 module Puppet::Parser::Functions
6   newfunction(:str2bool, :type => :rvalue, :doc => <<-EOS
7 This converts a string to a boolean. This attempt to convert strings that
8 contain things like: Y,y, 1, T,t, TRUE,true to 'true' and strings that contain things
9 like: 0, F,f, N,n, false, FALSE, no to 'false'.
10     EOS
11   ) do |arguments|
12
13     raise(Puppet::ParseError, "str2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1
14
15     string = arguments[0]
16
17     # If string is already Boolean, return it
18     if !!string == string
19       return string
20     end
21
22     unless string.is_a?(String)
23       raise(Puppet::ParseError, 'str2bool(): Requires string to work with')
24     end
25
26     # We consider all the yes, no, y, n and so on too ...
27     result = case string
28       #
29       # This is how undef looks like in Puppet ...
30       # We yield false in this case.
31       #
32       when /^$/, '' then false # Empty string will be false ...
33       when /^(1|t|y|true|yes)$/i  then true
34       when /^(0|f|n|false|no)$/i  then false
35       when /^(undef|undefined)$/ then false # This is not likely to happen ...
36       else
37         raise(Puppet::ParseError, 'str2bool(): Unknown type of boolean given')
38     end
39
40     return result
41   end
42 end
43
44 # vim: set ts=2 sw=2 et :