4 module Puppet::Parser::Functions
5 newfunction(:convert_base, :type => :rvalue, :arity => 2, :doc => <<-'DOC') do |args|
6 Converts a given integer or base 10 string representing an integer to a specified base, as a string.
10 $binary_repr = convert_base(5, 2) # $binary_repr is now set to "101"
11 $hex_repr = convert_base("254", "16") # $hex_repr is now set to "fe"
13 Note: Since Puppet 4.5.0 this can be done with String.new() and its many formatting options:
15 $binary_repr = String(5, '%b') # results in "101"
16 $hex_repr = String(254, "%x") # results in "fe"
17 $hex_repr = String(254, "%#x") # results in "0xfe"
20 raise Puppet::ParseError, 'convert_base(): First argument must be either a string or an integer' unless args[0].is_a?(Integer) || args[0].is_a?(String)
21 raise Puppet::ParseError, 'convert_base(): Second argument must be either a string or an integer' unless args[1].is_a?(Integer) || args[1].is_a?(String)
23 if args[0].is_a?(String)
24 raise Puppet::ParseError, 'convert_base(): First argument must be an integer or a string corresponding to an integer in base 10' unless args[0] =~ %r{^[0-9]+$}
27 if args[1].is_a?(String)
28 raise Puppet::ParseError, 'convert_base(): First argument must be an integer or a string corresponding to an integer in base 10' unless args[1] =~ %r{^[0-9]+$}
31 number_to_convert = args[0]
34 number_to_convert = number_to_convert.to_i
35 new_base = new_base.to_i
37 raise Puppet::ParseError, 'convert_base(): base must be at least 2 and must not be greater than 36' unless new_base >= 2 && new_base <= 36
39 return number_to_convert.to_s(new_base)