1

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

<? 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()) ?>

有可能与Ruby有关吗?你会怎么做?


更新

以下代码等效于 PHP 代码:

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)

有办法ruby file.erb >> output.fmt吗?


更新2

标准 Ruby 发行版具有erb处理器

/usr/bin/erb  my_formatted_file.erb
4

1 回答 1

1

有几种方法可以做到这一点,但最常见的可能是erb。这允许您提供一个模板,然后在 <% %> 符号中嵌入 ruby​​ 命令。与使用 PHP 的方式大致相同。这就是大多数 Ruby-On-Rails 应用程序呈现其视图的方式。

这里有 19 种不同的 ruby​​ 模板引擎(其中一些是 XML/HTML 特定的)的简短回顾

于 2010-06-04T09:03:32.947 回答