Class: EmuPower::StreamParser::Parser

Inherits:
Nokogiri::XML::SAX::Document
  • Object
show all
Defined in:
lib/emu_power/stream_parser.rb

Overview

Nokogiri parser definition. Processes a flat XML stream with multiple roots.

Instance Method Summary collapse

Constructor Details

#initialize(fakeroot, roots, &block) ⇒ Parser

Initialize the set of root tags to consider



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/emu_power/stream_parser.rb', line 38

def initialize(fakeroot, roots, &block)

	@roots = roots

	@current_object = nil
	@current_property = nil
	@current_root = nil

	@callback = block

	# All element parsers ignore this tag. This is only
	# used to persuade Nokogiri to parse multiple roots
	# in a single stream without getting mad.
	@fakeroot = fakeroot

end

Instance Method Details

#characters(str) ⇒ Object

Populate the content of the current element



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/emu_power/stream_parser.rb', line 72

def characters(str)
	if @current_object != nil && @current_property != nil

		#cur = @current_object[@current_property]
		#return if cur == str

		# Wrap into array if we already have a value (XML permits duplicates)
		#cur = [cur] unless cur == nil
		
		#if cur.kind_of?(Array)
		#	cur << str
		#else
		#	cur = str
		#end

		#@current_object[@current_property] = cur

		@current_object[@current_property] = str

	end
end

#end_element(name, attrs = []) ⇒ Object

Close out the current tag and clear context



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/emu_power/stream_parser.rb', line 95

def end_element(name, attrs = [])

	return if name == @fakeroot
	
	if @current_root == name

		if @callback != nil
			@callback.call(@current_object)
		else
			puts "DEBUG: #{@current_object}"
		end
		
		@current_object = nil
		@current_root = nil

	elsif @current_object != nil
		@current_property = nil
	end

end

#start_element(name, attrs = []) ⇒ Object

For each tag, initialize a root element if we don’t already have one. Otherwise, consider it a property of the current element.



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/emu_power/stream_parser.rb', line 57

def start_element(name, attrs = [])

	return if name == @fakeroot
	return if @current_object == nil && !@roots.include?(name)

	if @current_object == nil
		@current_root = name
		@current_object = { "MessageType" => name }
	else
		@current_property = name
	end

end