解析像红宝石
问题描述:
文件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"}]
任何帮助或方向?
答
这是我想出的。首先,使用:
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
对象(除非它已经解析某个节)。任何其他非注释行都会被解析为测试用例。
谢谢!无论如何,它正在为每个测试用例创建一个新的部分。它应该是1:N关系而不是1:1。像一个部分(一个参数)和很多测试用例 – 2014-10-27 08:04:13
我不确定你的意思。正如你可以从我的输出中看到的那样,它每节有多个测试用例。 – 2014-10-29 01:39:25
没关系。你的帮助够了,谢谢! – 2014-10-29 08:49:48