class IniParse::Parser

Public Class Methods

new(source) click to toggle source

Creates a new Parser instance for parsing string source.

Parameters

source<String>

The source string.

# File lib/iniparse/parser.rb, line 31
def initialize(source)
  @source = source.dup
end
parse_line(line) click to toggle source

Takes a raw line from an INI document, striping out any inline comment, and indent, then returns the appropriate tuple so that the Generator instance can add the line to the Document.

Raises

IniParse::ParseError: If the line could not be parsed.

# File lib/iniparse/parser.rb, line 56
def parse_line(line)
  sanitized, opts = strip_indent(*strip_comment(line, {}))

  parsed = nil
  @@parse_types.each do |type|
    break if (parsed = type.parse(sanitized, opts))
  end

  if parsed.nil?
    raise IniParse::ParseError,
      "A line of your INI document could not be parsed to a " \
      "LineType: #{line.inspect}."
  end

  parsed
end
parse_types() click to toggle source

Returns the line types.

Returns

Array

# File lib/iniparse/parser.rb, line 9
def self.parse_types
  @@parse_types ||= []
end
parse_types=(types) click to toggle source

Private Class Methods

strip_comment(line, opts) click to toggle source

Strips in inline comment from a line (or value), removes trailing whitespace and sets the comment options as applicable.

# File lib/iniparse/parser.rb, line 79
def strip_comment(line, opts)
  if m = /^(^)(?:(;|\#)(\s*)(.*))$$/.match(line) ||
     m = /^(.*?)(?:\s+(;|\#)(\s*)(.*))$/.match(line) # Comment lines.
    opts[:comment] = m[4].rstrip
    opts[:comment_prefix] = m[3]
    opts[:comment_sep] = m[2]
    # Remove the line content (since an option value may contain a
    # semi-colon) _then_ get the index of the comment separator.
    opts[:comment_offset] =
      line[(m[1].length..-1)].index(m[2]) + m[1].length

    line = m[1]
  else
    line = line.chomp
  end

  [line, opts]
end
strip_indent(line, opts) click to toggle source

Removes any leading whitespace from a line, and adds it to the options hash.

# File lib/iniparse/parser.rb, line 100
def strip_indent(line, opts)
  if m = /^(\s+).*$/.match(line)
    line.lstrip!
    opts[:indent] = m[1]
  end

  [line, opts]
end

Public Instance Methods

parse() click to toggle source

Parses the source string and returns the resulting data structure.

Returns

IniParse::Document

# File lib/iniparse/parser.rb, line 40
def parse
  IniParse::Generator.gen do |generator|
    @source.split("\n", -1).each do |line|
      generator.send(*Parser.parse_line(line))
    end
  end
end