Puppet Function: hash2ini

Defined in:
lib/puppet/functions/hash2ini.rb
Function type:
Ruby 4.x API

Summary

Converts a puppet hash to INI file string.

Overview

hash2ini(Hash $input, Optional[Hash] $options)String

Examples:

Call the function with the $input and $options hashes

hash2ini($input, $options)

Parameters:

  • input (Hash)

    The hash to be converted to INI file

  • options (Optional[Hash])

    A hash of options to control INI file format

Returns:

  • (String)

    An INI file formatted string



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/puppet/functions/hash2ini.rb', line 2

Puppet::Functions.create_function(:hash2ini) do
  # @param input The hash to be converted to INI file
  # @param options A hash of options to control INI file format
  # @return [String] An INI file formatted string
  # @example Call the function with the $input and $options hashes
  #   hash2ini($input, $options)
  dispatch :ini do
    param 'Hash', :input
    optional_param 'Hash', :options
  end

  def ini(input, options = {})
    settings = {
      'header'            => '# THIS FILE IS CONTROLLED BY PUPPET',
      'section_prefix'    => '[',
      'section_suffix'    => ']',
      'key_val_separator' => '=',
      'quote_char'        => '"',
      'quote_booleans'    => true,
      'quote_numerics'    => true,
    }

    settings.merge!(options)

    output = []
    output << settings['header'] << nil
    input.each_key do |section|
      output << "#{settings['section_prefix']}#{section}#{settings['section_suffix']}"
      input[section].each do |k, v|
        v_is_a_boolean = (v.is_a?(TrueClass) || v.is_a?(FalseClass))
        output << if (v_is_a_boolean && !settings['quote_booleans']) || (v.is_a?(Numeric) && !settings['quote_numerics'])
                    "#{k}#{settings['key_val_separator']}#{v}"
                  else
                    "#{k}#{settings['key_val_separator']}#{settings['quote_char']}#{v}#{settings['quote_char']}"
                  end
      end
      output << nil
    end
    output.join("\n")
  end
end