Update puppetlabs/stdlib module
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / bool2str.rb
1 #
2 # bool2str.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(:bool2str, :type => :rvalue, :doc => <<-DOC
6     Converts a boolean to a string using optionally supplied arguments. The
7     optional second and third arguments represent what true and false will be
8     converted to respectively. If only one argument is given, it will be
9     converted from a boolean to a string containing 'true' or 'false'.
10
11     *Examples:*
12
13     bool2str(true)                    => 'true'
14     bool2str(true, 'yes', 'no')       => 'yes'
15     bool2str(false, 't', 'f')         => 'f'
16
17     Requires a single boolean as an input.
18
19     Note that since Puppet 5.0.0 it is possible to create new data types for almost any
20     datatype using the type system and the built-in
21     [`String.new`](https://puppet.com/docs/puppet/latest/function.html#boolean-to-string)
22     function is used to convert to String with many different format options.
23
24         notice(String(false))         # Notices 'false'
25         notice(String(true))          # Notices 'true'
26         notice(String(false, '%y'))   # Notices 'yes'
27         notice(String(true, '%y'))    # Notices 'no'
28
29     DOC
30              ) do |arguments|
31
32     unless arguments.size == 1 || arguments.size == 3
33       raise(Puppet::ParseError, "bool2str(): Wrong number of arguments given (#{arguments.size} for 3)")
34     end
35
36     value = arguments[0]
37     true_string = arguments[1] || 'true'
38     false_string = arguments[2] || 'false'
39     klass = value.class
40
41     # We can have either true or false, and nothing else
42     unless [FalseClass, TrueClass].include?(klass)
43       raise(Puppet::ParseError, 'bool2str(): Requires a boolean to work with')
44     end
45
46     unless [true_string, false_string].all? { |x| x.is_a?(String) }
47       raise(Puppet::ParseError, 'bool2str(): Requires strings to convert to')
48     end
49
50     return value ? true_string : false_string
51   end
52 end
53
54 # vim: set ts=2 sw=2 et :