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