Class: Teapot::Substitutions::NestedSubstitution

Inherits:
Object
  • Object
show all
Defined in:
lib/teapot/substitutions.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(keyword, open, close, indent = "\t") ⇒ NestedSubstitution

Returns a new instance of NestedSubstitution.



150
151
152
153
154
155
156
157
# File 'lib/teapot/substitutions.rb', line 150

def initialize(keyword, open, close, indent = "\t")
	@keyword = keyword

	@open = open
	@close = close

	@indent = indent
end

Class Method Details

.apply(text, group) ⇒ Object



231
232
233
234
235
236
237
# File 'lib/teapot/substitutions.rb', line 231

def self.apply(text, group)
	group.each do |substitution|
		text = substitution.apply(text)
	end
	
	return text
end

Instance Method Details

#apply(text, level = 0) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/teapot/substitutions.rb', line 203

def apply(text, level = 0)
	open_pattern = line_pattern
	close_pattern = line_pattern('/')

	lines = text.each_line
	output = StringIO.new

	indent = lambda do |level, indentation|
		while line = lines.next rescue nil
			if line =~ open_pattern
				write_open($1, $2, output, indentation)

				indent[level + @open.count, indentation.by(@open.count)]

				write_close($1, $2, output, indentation)
			elsif line =~ close_pattern
				break
			else
				output.write(indentation + line)
			end
		end
	end

	indent[0, Indentation.none]

	return output.string
end

#freezeObject



159
160
161
162
163
164
165
166
# File 'lib/teapot/substitutions.rb', line 159

def freeze
	@keyword.freeze
	@open.freeze
	@close.freeze
	@indent.freeze
	
	super
end

#line_pattern(prefix = '') ⇒ Object



168
169
170
171
172
173
# File 'lib/teapot/substitutions.rb', line 168

def line_pattern(prefix = '')
	tag_pattern = Regexp.escape('<' + prefix + @keyword + '>')
	
	# Line matching pattern:
	Regexp.new('^(.*?)' + tag_pattern + '(.*)$', Regexp::MULTILINE | Regexp::EXTENDED)
end

#write_close(prefix, postfix, output, indentation) ⇒ Object



189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/teapot/substitutions.rb', line 189

def write_close(prefix, postfix, output, indentation)
	depth = @close.size
	indentation = indentation.with_prefix(prefix)

	#output.write(prefix)
	(0...depth).reverse_each do |i|
		chunk = @close[-1 - i]
		chunk.chomp! if i == 0
		
		output.write(indentation.by(i) << chunk)
	end
	output.write(postfix)
end

#write_open(prefix, postfix, output, indentation) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/teapot/substitutions.rb', line 175

def write_open(prefix, postfix, output, indentation)
	depth = @open.size
	indentation = indentation.with_prefix(prefix)

	#output.write(prefix)
	(0...depth).each do |i|
		chunk = @open[i]
		chunk.chomp! if i == depth-1
		
		output.write(indentation.by(i) << chunk)
	end
	output.write(postfix)
end