Class: Trenni::Template::Scanner

Inherits:
StringScanner show all
Defined in:
lib/trenni/template.rb

Constant Summary collapse

TEXT =

This is formulated specifically so that it matches up until the start of a code block.

/([^<#]|<(?!\?r)|#(?!\{)){1,}/m

Constants inherited from StringScanner

StringScanner::STUCK_MESSAGE

Instance Attribute Summary

Attributes inherited from StringScanner

#buffer

Instance Method Summary collapse

Methods inherited from StringScanner

#parse_error!, #path, #raise_if_stuck, #stuck?

Constructor Details

#initialize(buffer, delegate) ⇒ Scanner

Returns a new instance of Scanner.



78
79
80
81
82
# File 'lib/trenni/template.rb', line 78

def initialize(buffer, delegate)
	super(buffer)
	
	@delegate = delegate
end

Instance Method Details

#parse!Object



84
85
86
87
88
89
90
91
92
93
# File 'lib/trenni/template.rb', line 84

def parse!
	until eos?
		start_pos = self.pos

		scan_text
		scan_expression or scan_interpolation
		
		raise_if_stuck(start_pos)
	end
end

#scan_expressionObject



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/trenni/template.rb', line 104

def scan_expression
	start_pos = self.pos
	
	if scan(/<\?r/)
		if scan_until(/(.*?)\?>/m)
			@delegate.expression(self[1])
		else
			parse_error!("Could not find end of expression!", [start_pos, self.pos])
		end
		
		return true
	end
	
	return false
end

#scan_interpolationObject



120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/trenni/template.rb', line 120

def scan_interpolation
	start_pos = self.pos
	
	if scan(/\#\{/)
		level = 1
		code = String.new

		until eos?
			current_pos = self.pos
			
			# Scan anything other than something which causes nesting:
			if scan(/[^"'\{\}]+/m)
				code << matched
			end
			
			# Scan a quoted string:
			if scan(/'(\\'|[^'])*'/m) or scan(/"(\\"|[^"])*"/m)
				code << matched
			end
			
			# Scan something which nests:
			if scan(/\{/)
				code << matched
				level += 1
			end

			if scan(/\}/)
				level -= 1
				if level == 0
					@delegate.interpolation(code)
					return true
				else
					code << matched
				end
			end
			
			break if stuck?(current_pos)
		end
		
		parse_error!("Could not find end of interpolation!", [start_pos, self.pos])
	end
	
	return false
end

#scan_textObject



98
99
100
101
102
# File 'lib/trenni/template.rb', line 98

def scan_text
	if scan(TEXT)
		@delegate.text(self.matched)
	end
end