PageRenderTime 44ms CodeModel.GetById 37ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/tools/Rake/quicktemplate.rb

http://github.com/agross/netopenspace
Ruby | 48 lines | 37 code | 11 blank | 0 comment | 1 complexity | 28628ba21f3aeb820a25aa629dd9c196 MD5 | raw file
 1require 'rake'
 2require 'erb'
 3
 4class QuickTemplate
 5	attr_reader :args, :file
 6	
 7	def initialize(file)
 8		raise "The template file to process must be given" if file.nil?
 9
10		@file = file
11	end
12	
13	def exec(args = {})
14		template = prepare_template File.read(@file)
15		result = exec_erb template, args
16		
17		resultFile = @file.ext('')
18		File.open(resultFile, 'w') do
19			|f| f.write(result)
20		end
21		
22		puts "Created file #{resultFile}"
23	end
24	
25	def prepare_template(template)
26		tag_regex = /(@\w[\w\.]+\w@)/
27		
28		hits = template.scan(tag_regex)
29		tags = hits.map do |item|
30			item[0].chomp('@').reverse.chomp('@').reverse.strip
31		end
32		
33		tags.map! do |a|
34			a.to_sym
35		end
36		tags.uniq!
37
38		tags.inject(template) do |text, tag|
39			text.gsub /@#{tag.to_s}@/, "<%= #{tag.to_s} %>"
40		end
41	end
42		
43	def exec_erb(template, args)
44		b = binding
45		erb = ERB.new(template, 0, "%")
46		erb.result(b)
47	end
48end