]> git.donarmstrong.com Git - dsa-puppet.git/blob - modules/stdlib/lib/puppet/parser/functions/bool2num.rb
upgrade to concat 2.0.0
[dsa-puppet.git] / modules / stdlib / lib / puppet / parser / functions / bool2num.rb
1 #
2 # bool2num.rb
3 #
4
5 module Puppet::Parser::Functions
6   newfunction(:bool2num, :type => :rvalue, :doc => <<-EOS
7     Converts a boolean to a number. Converts the values:
8       false, f, 0, n, and no to 0
9       true, t, 1, y, and yes to 1
10     Requires a single boolean or string as an input.
11     EOS
12   ) do |arguments|
13
14     raise(Puppet::ParseError, "bool2num(): Wrong number of arguments " +
15       "given (#{arguments.size} for 1)") if arguments.size < 1
16
17     value = arguments[0]
18     klass = value.class
19
20     # We can have either true or false, or string which resembles boolean ...
21     unless [FalseClass, TrueClass, String].include?(klass)
22       raise(Puppet::ParseError, 'bool2num(): Requires either ' +
23         'boolean or string to work with')
24     end
25
26     if value.is_a?(String)
27       # We consider all the yes, no, y, n and so on too ...
28       value = case value
29         #
30         # This is how undef looks like in Puppet ...
31         # We yield 0 (or false if you wish) in this case.
32         #
33         when /^$/, '' then false # Empty string will be false ...
34         when /^(1|t|y|true|yes)$/  then true
35         when /^(0|f|n|false|no)$/  then false
36         when /^(undef|undefined)$/ then false # This is not likely to happen ...
37         else
38           raise(Puppet::ParseError, 'bool2num(): Unknown type of boolean given')
39       end
40     end
41
42     # We have real boolean values as well ...
43     result = value ? 1 : 0
44
45     return result
46   end
47 end
48
49 # vim: set ts=2 sw=2 et :