Class: Sawtooth::Parser

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

Overview

Default Parser implementation, can be used as a starting point for custom implementations.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Parser

Creates a new instance.



17
18
19
# File 'lib/sawtooth/parser.rb', line 17

def initialize(options = {})
  @rules = options[:rules] || Sawtooth::Rules::Set.new
end

Instance Attribute Details

#rulesObject (readonly)

Array of accessible rules.



14
15
16
# File 'lib/sawtooth/parser.rb', line 14

def rules
  @rules
end

Instance Method Details

#add(path, rule) ⇒ Object

Delegates to ‘Rules::Set#add`.



22
23
24
# File 'lib/sawtooth/parser.rb', line 22

def add(path, rule)
  rules.add(path, rule)
end

#comment(path, doc, str) ⇒ Object

Recieved a comment node.



27
# File 'lib/sawtooth/parser.rb', line 27

def comment(path, doc, str); end

#end_document(path, doc) ⇒ Object

End document callback



36
37
38
39
# File 'lib/sawtooth/parser.rb', line 36

def end_document(path, doc)
  rule = rules.find('@document:after')
  rule.finish(path.join('/'), doc, nil) if rule && rule.respond_to?(:finish)
end

#end_element(path, doc, node) ⇒ Object

End document callback



48
49
50
51
# File 'lib/sawtooth/parser.rb', line 48

def end_element(path, doc, node)
  rule = rules.find(path)
  rule.finish(path.join('/'), doc, node) if rule && rule.respond_to?(:finish)
end

#error(path, doc, message) ⇒ Object



53
54
55
# File 'lib/sawtooth/parser.rb', line 53

def error(path, doc, message)
  raise message
end

#parse(thing, encoding = 'UTF-8') ⇒ Object

Parses and XML thingy, a filename, path, IO or content from memory. Provides and optional encoding, which defaults to ‘UTF-8`.



60
61
62
63
64
65
# File 'lib/sawtooth/parser.rb', line 60

def parse(thing, encoding = 'UTF-8')
  Sawtooth::Document.new(self).tap do |doc|
    sax_parser = Nokogiri::XML::SAX::Parser.new(doc, encoding)
    sax_parser.parse(thing)
  end
end

#start_document(path, doc) ⇒ Object

Start document callback



30
31
32
33
# File 'lib/sawtooth/parser.rb', line 30

def start_document(path, doc)
  rule = rules.find('@document:before')
  rule.start(path.join('/'), doc, nil) if rule && rule.respond_to?(:start)
end

#start_element(path, doc, node) ⇒ Object

Start element callback



42
43
44
45
# File 'lib/sawtooth/parser.rb', line 42

def start_element(path, doc, node)
  rule = rules.find(path)
  rule.start(path.join('/'), doc, node) if rule && rule.respond_to?(:start)
end