Class: HTOTConv::Parser::SimpleText

Inherits:
Base
  • Object
show all
Defined in:
lib/htot_conv/parser/simple_text.rb

Instance Attribute Summary

Attributes inherited from Base

#option

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from HTOTConv::Parser::Base

Class Method Details

.option_helpObject



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
# File 'lib/htot_conv/parser/simple_text.rb', line 7

def self.option_help
  {
    :indent => {
      :default => "\t",
      :pat => String,
      :desc => "indent character (default: TAB)",
    },
    :delimiter => {
      :default => nil,
      :pat => String,
      :desc => "separator character of additional data",
    },
    :preserve_empty_line => {
      :default => false,
      :pat => FalseClass,
      :desc => "preserve empty line as a level-1 item (default: no)",
    },
    :key_header => {
      :default => [],
      :pat => Array,
      :desc => "key header",
    },
    :value_header => {
      :default => [],
      :pat => Array,
      :desc => "value header",
    },
  }
end

Instance Method Details

#parse(input) ⇒ Object



37
38
39
40
41
42
43
44
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/htot_conv/parser/simple_text.rb', line 37

def parse(input)
  indent_regexp = Regexp.new("^(?<indents>(#{Regexp.escape(@option[:indent])})*)")
  delimiter_regexp = (@option[:delimiter].kind_of?(String))? Regexp.new(Regexp.escape(@option[:delimiter])) : @option[:delimiter]
  outline = HTOTConv::Outline.new
  outline.key_header = @option[:key_header]
  outline.value_header = @option[:value_header]

  input.each_line do |line|
    next if ((line.chomp == "") && (!@option[:preserve_empty_line]))

    level = 1
    value = []
    if (@option[:indent] || '').length > 0
      indents = indent_regexp.match(line)[:indents]
      level = 1 + indents.length / @option[:indent].length
      line = line.sub(indent_regexp, "")
    end

    line = line.strip
    if delimiter_regexp
      key = line.split(delimiter_regexp)[0]
      value = line.split(delimiter_regexp)[1..-1] || []
    else
      key = line
    end

    outline.add_item(key, level, value)
  end

  outline
end