From: ptkwt@...1.aracnet.com (Phil Tomson) Date: 2001-10-29T12:40:35+09:00 Subject: [ruby-talk:23706] Re: Simple templating system (Oops... some bugs here) In article , Phil Tomson wrote: >In article , >David Alan Black wrote: Actually, there are a few problems here - that'll teach me to test more before posting ;-) The main thing is that the #>IF #{condition} doesn't work right. See comments below in the code: >Here's the code I came up with to do this: > >#template.rb >class String > def interpolate(bind) > eval (self.inspect,bind) > end >end > >class TemplateFile > attr_reader :fileString > def initialize(file,bind) > @stateArray = Array.new > @stateArray << true #default read state > @fileString = "" > @bind = bind > File.foreach(file) {|line| > case line > when /^#>IF/ > #check condition > condition = line.gsub(/#>IF/,"").strip > puts "condition is: "+condition if $DEBUG The 'condition.interpolate(@bind)' below always returns a String with either "true" or "false" - not a TrueClass or FalseClass type.... I wonder why I can't eval the resulting string and get a TrueClass or FalseClass - it doesn't seem to work like that, though. > @stateArray << condition.interpolate(@bind) > puts "#{line} : #{@stateArray.to_s}" if $DEBUG > when /^#>ELSE/ > #invert condition > @stateArray[-1] = !@stateArray[-1] > when /^#>END/ > @stateArray.pop > when /^#>INCLUDE/ > fields = line.split > file = fields[1].strip > puts "file to include is: #{file}" ....So the following tests will always come out true and will always be done even if the condition tested was false... > @fileString << include(fields[1].strip) if @stateArray.last > else @fileString << line if @stateArray.last > end > } > end > > def include(file) > tf = TemplateFile.new(file,@bind) > tf.fileString > end > > def interpolate(b=nil) > if b > @fileString.interpolate(b) > else > @fileString.interpolate(@bind) > end > end > >end > >if $0 == __FILE__ > var = "string" > tf = TemplateFile.new("vhdl",binding) > #test different vector lengths: > 5.times do |i| > puts "for #{i}:" > puts tf.interpolate(binding) > end >end >#end Template.rb > > >BTW: the code in template.rb above also can handle some 'directives': Another problem with the #>IF #{condition} is that if the condition has changed since the file was read (say the condition is: #{i>2} and now after the file was read, i has changed) it won't be reflected in the results. So this part is not currently working (the solution is to re-read the file everytime). >#>IF #{condition} >#>ELSE >#>END > But this does work... >#>INCLUDE - reads in a specified file and includes it. I'll fix these bugs and repost... maybe I'll put it on the RAA or cookbook. Phil