Class: Newstile::Parser::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/newstile/parser/base.rb

Overview

Base class for parsers

This class serves as base class for parsers. It provides common methods that can/should be used by all parsers, especially by those using StringScanner for parsing.

Direct Known Subclasses

Html, Newstile

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(doc) ⇒ Base

Initialize the parser with the given Newstile document doc.



35
36
37
38
# File 'lib/newstile/parser/base.rb', line 35

def initialize(doc)
  @doc = doc
  @text_type = :text
end

Class Method Details

.parse(source, doc) ⇒ Object

Parse the source string into an element tree, using the information provided by the Newstile document doc.

Initializes a new instance of the calling class and then calls the #parse method that must be implemented by each subclass.



46
47
48
# File 'lib/newstile/parser/base.rb', line 46

def self.parse(source, doc)
  new(doc).parse(source)
end

Instance Method Details

#adapt_source(source) ⇒ Object

Modify the string source to be usable by the parser.



58
59
60
# File 'lib/newstile/parser/base.rb', line 58

def adapt_source(source)
  source.gsub(/\r\n?/, "\n").chomp + "\n"
end

#add_text(text, tree = @tree, type = @text_type) ⇒ Object

This helper method adds the given text either to the last element in the tree if it is a type element or creates a new text element with the given type.



64
65
66
67
68
69
70
# File 'lib/newstile/parser/base.rb', line 64

def add_text(text, tree = @tree, type = @text_type)
  if tree.children.last && tree.children.last.type == type
    tree.children.last.value << text
  elsif !text.empty?
    tree.children << Element.new(type, text)
  end
end

#extract_string(range, strscan) ⇒ Object

Extract the part of the StringScanner srcscan backed string specified by the range. This method also works correctly under Ruby 1.9.



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/newstile/parser/base.rb', line 74

def extract_string(range, strscan)
  result = nil
  if RUBY_VERSION >= '1.9'
    begin
      enc = strscan.string.encoding
      strscan.string.force_encoding('ASCII-8BIT')
      result = strscan.string[range].force_encoding(enc)
    ensure
      strscan.string.force_encoding(enc)
    end
  else
    result = strscan.string[range]
  end
  result
end

#warning(text) ⇒ Object

Add the given warning text to the warning array of the Newstile document.



52
53
54
55
# File 'lib/newstile/parser/base.rb', line 52

def warning(text)
  @doc.warnings << text
  #TODO: add position information
end