在脚本完成之前执行Ruby系统调用

时间:2011-06-08 15:44:32

标签: ruby erb pdflatex

我有一个Ruby脚本,它使用erb模板生成Latex文档。生成.tex文件后,我想进行系统调用以使用pdflatex编译文档。以下是剧本的骨头:

class Book
  # initialize the class, query a database to get attributes, create the book, etc.
end

my_book = Book.new
tex_file = File.open("/path/to/raw/tex/template")
template = ERB.new(tex_file.read)
f = File.new("/path/to/tex/output.tex")
f.puts template.result
system "pdflatex /path/to/tex/output.tex"

system行使我处于交互式tex输入模式,就像文档是空的一样。如果我删除了呼叫,则正常生成文档。如何确保在生成文档之后才进行系统调用?与此同时,我只是使用调用ruby脚本的bash脚本,然后使用pdflatex来解决问题。

1 个答案:

答案 0 :(得分:5)

File.new将打开一个不会关闭(保存到磁盘)的新流,直到脚本结束,直到您手动关闭它。

这应该有效:

...
f = File.new("/path/to/tex/output.tex")
f.puts template.result
f.close
system "pdflatex /path/to/tex/output.tex"

或者更友好的方式:

...
File.open("/path/to/tex/output.tex", 'w') do |f|
  f.puts template.result
end

system "pdflatex /path/to/tex/output.tex"

带有块的File.open将打开流,通过块变量(在此示例中为f)访问流,并在块执行后自动关闭流。 'w'将打开或创建文件(如果文件已存在,则内容将被删除=>该文件将被截断)

相关问题