用ruby解析类似ini的文件
我有一个以下格式的文件:用ruby解析类似ini的文件,ruby,parsing,Ruby,Parsing,我有一个以下格式的文件: [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 ... 这是一个测试框架。标题(关于[]的部分设置参数,然后以下字段是测
[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解析它们。所以基本上我做了以下工作(和C中的一样):
不过,我想以ruby的方式将其移植到ruby:将其组织为类
我想知道是否有任何框架(ini解析,没有帮助)来做这件事。。有什么想法、框架(树梢、柑橘有点过分)或片段可以帮助我吗
我想是这样的:
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“mytests.txt”
t、 解析
t、 第一节
=>
“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"}>
这段代码的大部分是解析代码。它查找以
[
开头的行,并创建一个新的节
对象(除非它已经在分析一个节)。任何其他非注释行都将作为测试用例进行分析。谢谢!但是,它为每个测试用例创建一个新节。它应该是1:N关系,而不是1: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"}>
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