使用 Ruby 生成格式化文件,就像使用 PHP 一样
我使用 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()) ?>
Is it possible to do with 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 >>>输出.fmt?
Update2
标准 Ruby 发行版具有 erb
处理器
/usr/bin/erb my_formatted_file.erb
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有多种方法可以做到这一点,但最常见的可能是 erb.这允许您提供一个模板,然后将 ruby 命令嵌入到 <% %> 中。符号。与使用 PHP 的方式非常相似。这就是大多数 Ruby-On-Rails 应用程序呈现视图的方式。
有 19 种不同的 ruby 模板引擎(其中一些是 XML/HTML 特定的)的简短评论 此处
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