Class: Mist::CodeExampleParser

Inherits:
Object
  • Object
show all
Defined in:
lib/mist/code_example_parser.rb

Defined Under Namespace

Classes: Example

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content) ⇒ CodeExampleParser

Returns a new instance of CodeExampleParser.



37
38
39
40
# File 'lib/mist/code_example_parser.rb', line 37

def initialize(content)
  @content = content.to_s.dup
  @examples = parse
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



2
3
4
# File 'lib/mist/code_example_parser.rb', line 2

def content
  @content
end

#examplesObject (readonly)

Returns the value of attribute examples.



2
3
4
# File 'lib/mist/code_example_parser.rb', line 2

def examples
  @examples
end

Instance Method Details

#parseObject



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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/mist/code_example_parser.rb', line 42

def parse
  in_example = false
  offset = 0
  
  [].tap do |examples|
    while match = /^    ([^\n]+(\n|\z))/m.match(content[offset..-1])
      in_example = examples.last && match.offset(0)[0] == 0 && offset > 0
      examples << Example.new(match.offset(0)[0]+offset) unless in_example
      line = match[1]
      examples.last.whitespace_skipped += 4
      examples.last.concat match[1]

      offset += match.offset(0)[1]
    end
    
    # detect multiple examples separated only by white space
    # -- they are part of the same example
    pass = proc do
      call_again = false
      examples.length.times do |index|
        current = examples[index]
        next if index == 0 or current.explicit_filename
        
        previous = examples[index-1]
        min = previous.offset.max
        max = current.offset.min
        
        if content[(min+1)...max] =~ /\A[\s\t\n]*\z/
          previous.whitespace_skipped += current.whitespace_skipped
          previous.concat $~[0] + current
          examples.delete current
          call_again = true
          break
        end
      end

      pass.call if call_again
    end
    pass.call
    
    # Last pass: assign default filenames as needed
    examples.each_with_index { |example, index| example.filename ||= "Example #{index+1}" }
  end
end