部分文件的读取行?

时间:2015-01-26 22:09:22

标签: ruby-on-rails ruby

我正在测试一个Rails函数,它在遇到错误时会在日志文件中留下几个不同的消息。测试是为了确保在适当的情况下记录正确的消息。

此日志文件非常大;我希望能够做的就是忽略在运行测试之前不存在的所有行,然后搜索由我的测试操作生成的剩余部分,以便我不会这样做#39 ; t必须将整个文件填入内存。

这可行吗?

2 个答案:

答案 0 :(得分:1)

您可以在测试开始时获取文件大小,然后seek获取文件大小:

the_log = Rails.root.join("log", "test.log")
size_at_start = the_log.size
... test stuff ...
File.open(the_log) do |f|
  # Skip to the point in the log where our test started
  f.seek(size_at_the_start)
  while line = f.gets
    # We found what we were looking for
    break if line =~ /required message/
  end
  fail("We haven't found what we were looking for")
end

如果你真的想干它,你可以在你的测试助手中使用这个方法,例如:

def test_log_output(required_output_regexp, 
                    the_log = Rails.root.join("log", "test.log"), 
                    &test_code)
  size_at_start = the_log.size
  test_code.call
  File.open(the_log) do |f|
    f.seek(size_at_the_start)
    while line = f.gets
      # We found what we were looking for
      break if line =~ required_output_regexp
    end
    fail("We haven't found what we were looking for")
  end
end

答案 1 :(得分:0)

虽然不完全是答案,但另一个s.o.问题 - Insert rows on specific line in a file - 突出了一些可以帮助你做你想做的方法(readline,seek)。