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