2014-10-26 141 views
0

文件INI我有以下格式的文件:解析像紅寶石

[X:10] 
[Y:20] 
# many of them, they are test parameters 
C = 1 
A = 1234 
B = 12345 
.... 
# many of them, they are test cases 

# new test parameters 
[X:20] 
[Y:40] 
# new test cases 
C = 1 
A = 1234 
B = 12345 
... 

這是一個測試框架。報頭(在[]部分中設置的參數,然後將以下字段測試用例)

我今天解析它們在C.所以基本上i執行以下操作(如常在C):

while(fgets(....) 
    if(!strcmp(keyword,"[X")) 
    x = atoi(value); 

但是我想用紅寶石的方式將它轉換成ruby:將它組織成類。

我想知道是否有任何框架(ini parses,does not help)做它..任何想法,框架(樹梢,柑橘是有點矯枉過正)或片段,可以幫助我嗎?

不過,我覺得是這樣的:

class TestFile 
    attr_accessor :sections 
    def parse 
    end 
end 

# the test parameters value 
class Section 
    attr_accessor :entries, foo,bar.. # all accessible fields 
end 

# the test cases 
class Entry 
    attr_accessor #all accessible fields 
end 

那麼我可以用它喜歡:

t = TestFile.new "mytests.txt" 
t.parse 
t.sections.first 

=>  
<Section:0x000000014b6b70 @parameters={"X"=>"128", "Y"=>"96", "Z"=>"0"}, @cases=[{"A"=>"14", "B"=>"1", "C"=>"2598", "D"=>"93418"},{"A"=>"12", "B"=>"3", "C"=>"2198", "D"=>"93438"}] 

任何幫助或方向?

回答

1

這是我想出的。首先,使用:

t = Testfile.new('ini.txt') 
t.parse 

t.sections.count 
#=>2 

t.sections.first 
#=> #<Section:0x00000002d74b30 @parameters={"X"=>"10", "Y"=>"20"}, @cases={"C"=>"1", "A"=>"1234", "B"=>"12345"}> 

正如你所看到的,我所做的Section同時包含參數和案件 - 只是一個主觀判斷,它可以做其他的方式。執行:

class Testfile 
    attr_accessor :filename, :sections 

    def initialize(filename) 
    @sections = [] 
    @filename = filename 
    end 

    def parse 
    @in_section = false 
    File.open(filename).each_line do |line| 
     next if line =~ /^#?\s*$/ #skip comments and blank lines 
     if line.start_with? "[" 
     if not @in_section 
      @section = Section.new 
      @sections << @section 
     end 
     @in_section = true 
     key, value = line.match(/\[(.*?):(.*?)\]/).captures rescue nil 
     @section.parameters.store(key, value) unless key.nil? 
     else 
     @in_section = false 
     key, value = line.match(/(\w+) ?= ?(\d+)/).captures rescue nil 
     @section.cases.store(key, value) unless key.nil? 
     end 
    end 
    @sections << @section 
    end 
end 

class Section 
    attr_accessor :parameters, :cases 

    def initialize 
    @parameters = {} 
    @cases = {} 
    end 
end 

這段代碼大部分是解析。它會查找以[開頭的行並創建一個新的Section對象(除非它已經解析某個節)。任何其他非註釋行都會被解析爲測試用例。

+0

謝謝!無論如何,它正在爲每個測試用例創建一個新的部分。它應該是1:N關係而不是1:1。像一個部分(一個參數)和很多測試用例 – 2014-10-27 08:04:13

+0

我不確定你的意思。正如你可以從我的輸出中看到的那樣,它每節有多個測試用例。 – 2014-10-29 01:39:25

+1

沒關係。你的幫助夠了,謝謝! – 2014-10-29 08:49:48