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 " +
|
---|
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 ' +
|
---|
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)$/i then true
|
---|
36 | when /^(0|f|n|false|no)$/i 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 :
|
---|