Class: Giter8::Parsers::PairsParser

Inherits:
Object
  • Object
show all
Defined in:
lib/giter8/parsers/pairs_parser.rb

Overview

PairsParser implements an FSM for parsing a key-value string containing property pairs for rendering.

Constant Summary collapse

STATE_KEY =
0
STATE_VALUE =
1
STATE_COMMENT =
2
CHR_SPACE =
" "
CHR_TAB =
"\t"
CHR_CARRIAGE_RETURN =
"\r"
CHR_NEWLINE =
"\n"
CHR_HASH =
"#"
CHR_EQUAL =
"="
WHITE_CHARS =
[CHR_SPACE, CHR_TAB, CHR_CARRIAGE_RETURN, CHR_NEWLINE].freeze
ALPHA_REGEXP =
/[[:alpha:]]/.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ PairsParser

Initialises a new PairsParser instance. See also: PairsParser.parse



33
34
35
36
37
38
39
40
41
# File 'lib/giter8/parsers/pairs_parser.rb', line 33

def initialize(opts = {})
  @pairs = []
  @state = STATE_KEY
  @tmp_key = []
  @tmp_val = []
  @source = opts[:source] || "unknown"
  @column = 0
  @line = 1
end

Class Method Details

.parse(input, opts = {}) ⇒ Object

Parses a given key-value pair list within a string with provided options. Options is a hash that currently only supports the :source key, which must be the name of the file being parsed. This key is used to identify any errors whilst parsing the contents and will be provided on any raised errors. Returns an Pairs object with the read properties.



27
28
29
# File 'lib/giter8/parsers/pairs_parser.rb', line 27

def self.parse(input, opts = {})
  new(opts).parse(input)
end

Instance Method Details

#parse(input) ⇒ Object

Parses a given input string into key-value Pair objects. Returns an Pairs object of identified keys and values.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/giter8/parsers/pairs_parser.rb', line 45

def parse(input)
  input.chars.each do |chr|
    chr = chr.chr
    case @state
    when STATE_KEY
      parse_key(chr)

    when STATE_COMMENT
      @state = STATE_KEY if chr == CHR_NEWLINE

    when STATE_VALUE
      parse_value(chr)
    end

    @column += 1
    if chr == CHR_NEWLINE
      @line += 1
      @column = 0
    end
  end

  finish_parse
end