用ruby解析一个像ini的文件

时间:2014-10-26 20:12:18

标签: 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
...

这是一个测试框架。标题([]部分设置参数,然后以下字段是测试用例)

我今天用C解析它们。所以基本上我做了以下(像往常一样在C中):

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

然而我想以红宝石的方式将它移植到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"}] 

任何帮助或指示?

1 个答案:

答案 0 :(得分: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对象(除非它已经在解析一个部分)。任何其他非注释行都被解析为测试用例。

相关问题