Personal tools

Ruby examples

From MohidWiki

Revision as of 11:41, 2 June 2008 by 192.168.20.177 (talk)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

[ruby,Y] class IsTheRootStringToTransform

 attr_reader :rootfilecontent, :list, :matches 
 attr_reader :matchexpr, :j, :outfilename, :batch
 
 def initialize (rootstring, list)
   @rootfilecontent, @list = rootstring, list
   @list = @list.to_a if !@list.is_a?(Array)
   @matchexpr = @list.shift
   @matches = @matchexpr.tr('()',).split(' ')
   @closings = @matchexpr.gsub(/\(.+?\)/, '*').split(/\*| /)
   puts @closings.join(' ')
 end
 
 def isTransformedByTheBlock
   @j = 1
   @list.each do |line|
     yield line
     @j = @j + 1
   end
 end
 
 def buildHashOfSubs(array)
   hash = Hash.new
   array.size.times { |i| hash.store(@matches[i], @closings[2*i].chomp + array[i] + @closings[2*i + 1].chomp) }
   return hash
 end
 
 def isTransformedIntoFile(filename)
   
   @outfilename = filename
   isTransformedByTheBlock{ |line|    
     filecontent = String.new( @rootfilecontent )
     
     tokens = line.split( ' ' )
     subhash = buildHashOfSubs(tokens)
     subhash.each { |match, sub| filecontent.replace filecontent.gsub(match, sub) }
     
     mytrgfile = File.new(filename + "_" + @j.to_s.rjust(3,"0") + ".dat", "w")
     mytrgfile.puts filecontent
     mytrgfile.close
     
     puts filecontent
   }
   
 end
 
 def hasTheFollowingBatchFileBlock(batchfilename)
   
   @batch = String.new
   

batchhead = <<HEAD @echo off for %%i in (#{@outfilename}_*.dat) do ( HEAD

   yield
   

batchfoot = <<FOOT ) @echo on FOOT

   batchfile = File.new(batchfilename, "w")
   batchfile.puts batchhead + @batch + batchfoot
   batchfile.close
   
 end

end