Class: Philiprehberger::IniParser::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/ini_parser/parser.rb

Overview

Parses INI-formatted strings into nested Hashes.

Supports sections, global keys, comments (; and #), blank lines, quoted string values, inline comments, multiline values with backslash continuation, escape sequences, and automatic type coercion for booleans, integers, and floats.

Constant Summary collapse

SECTION_RE =
/\A\[([^\]]+)\]\z/
COMMENT_RE =
/\A\s*[;#]/
KV_RE =
/\A([^=]+)=(.*)?\z/
CONTINUATION_RE =
/\\\s*\z/
ESCAPE_MAP =
{
  'n' => "\n",
  't' => "\t",
  '\\' => '\\',
  ';' => ';',
  '#' => '#'
}.freeze

Instance Method Summary collapse

Instance Method Details

#parse(string, coerce_types: true) ⇒ Hash

Parse an INI string into a Hash.

Parameters:

  • string (String)

    INI content

  • coerce_types (Boolean) (defaults to: true)

    whether to coerce values to native types

Returns:

  • (Hash)

    parsed configuration

Raises:



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/philiprehberger/ini_parser/parser.rb', line 31

def parse(string, coerce_types: true)
  result = {}
  current_section = nil
  continuation_key = nil
  continuation_value = nil
  continuation_target = nil

  string.each_line do |raw_line|
    line = raw_line.strip

    if continuation_key
      continuation_value, continuation_key, continuation_target = handle_continuation(
        line, continuation_key, continuation_value, continuation_target, coerce_types
      )
      next
    end

    next if skip?(line)

    current_section, continuation_key, continuation_value, continuation_target = process_line(
      line, raw_line, result, current_section, coerce_types
    )
  end

  result
end