使用Ruby生成格式化文件的方式与PHP如何完成

问题描述:

I use PHP to generate files of some special format, and I have decided to try the same thing with Ruby. To make a file with PHP, I use the following code:

<? include 'functions_and_settings.php'; ob_start() ?>

some parts of another format

<? // php functions generating file content, 
   // including other formatted files ?>

some parts

<? file_put_contents('output.fmt', ob_get_clean()) ?>

Is it possible to do with Ruby? How would you do this?


Update

The following code is equivalent to the PHP one:

require 'erb'
require 'my_functions_and_settings'
template = ERB.new <<-EOF

some text lines of another format

<% #functions generating content,
   # inclusion of formatted files %>

some text lines of another format

EOF
File.open("output.fmt", "w") do |f|
  f.puts template.result(binding)
end
# or may be:  File.new("file.txt") << template.result(binding)

Is there a way to do ruby file.erb >> output.fmt?


Update2

Standard Ruby distribution has erb processor

/usr/bin/erb  my_formatted_file.erb

我使用PHP生成一些特殊格式的文件,我决定尝试用Ruby做同样的事情。 要使用PHP创建文件,我使用以下代码: p>

 &lt;? 包括'functions_and_settings.php';  ob_start()?&gt; 
 
some另一种格式的部分
 
&lt;?  // php函数生成文件内容,
 //包括其他格式化文件?&gt; 
 
some parts 
 
&lt;?  file_put_contents('output.fmt',ob_get_clean())?&gt; 
  code>  pre> 
 
 

是否可以使用Ruby? 你会怎么做? p>


更新 strong> p>

以下代码相当于 PHP one: p>

  require'erb'
require'my_functions_and_settings'
 
mpmplate = ERB.new&lt;&lt; -EOF 
 
some另一种格式的文本行
 \  n&lt;%#functions生成内容,
#包含格式化文件%&gt; 
 
some另一种格式的文本行
 
EOF 
File.open(“output.fmt”,“w”)do | f |  
 f.puts template.result(binding)
end 
#或者可能是:File.new(“file.txt”)&lt;&lt;  template.result(binding)
  code>  pre> 
 
 

有没有办法做 ruby​​ file.erb&gt;&gt; output.fmt code>? p>


Update2 strong> p>

标准Ruby发行版 erb code> processor p>

  / usr / bin / erb my_formatted_file.erb 
  code>  pre> 
  div>

There are several ways to do this but the most common is probably erb. This allows you to provide a template and then embed ruby command within <% %> symbols. In much the same way as you do with PHP. This is how most Ruby-On-Rails applications render their views.

There is a short review of 19 different ruby templating engines (Some of which are XML/HTML specific) available here