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'.
13 bool2str(true) => 'true'
14 bool2str(true, 'yes', 'no') => 'yes'
15 bool2str(false, 't', 'f') => 'f'
17 Requires a single boolean as an input.
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.
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'
32 unless arguments.size == 1 || arguments.size == 3
33 raise(Puppet::ParseError, "bool2str(): Wrong number of arguments given (#{arguments.size} for 3)")
37 true_string = arguments[1] || 'true'
38 false_string = arguments[2] || 'false'
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')
46 unless [true_string, false_string].all? { |x| x.is_a?(String) }
47 raise(Puppet::ParseError, 'bool2str(): Requires strings to convert to')
50 return value ? true_string : false_string
54 # vim: set ts=2 sw=2 et :