使用 Ruby 生成格式化文件,就像使用 PHP 一样

发布于 2024-09-04 14:36:24 字数 1072 浏览 3 评论 0原文

我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谁与争疯 2024-09-11 14:36:24

有多种方法可以做到这一点,但最常见的可能是 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文