我有以下Ruby脚本:
require 'erubis'
def listing(title, attributes={})
"output" + yield + "more output"
end
example = %Q{<% listing "db/migrate/[date]_create_purchases.rb", :id => "ch01_292" do %>
<![CDATA[class CreatePurchases < ActiveRecord::Migration
def change
create_table :purchases do |t|
t.string :name
t.float :cost
t.timestamps
end
end
end]]>
<% end %>}
chapter = Erubis::Eruby.new(example)
p chapter.result(binding)
Run Code Online (Sandbox Code Playgroud)
我试图在这里使用一个块并让它输出"输出",然后输出块中的内容然后"更多输出",但我似乎无法让它工作.
我知道ERB曾经在Rails 2.3中以这种方式工作,现在可以<%=在Rails 3中使用......但我根本不使用Rails.这只是纯ERB.
如何让它输出所有内容?
杰里米·麦卡纳利 (Jeremy McAnally) 将我与如何做到这一点的完美描述联系起来。
基本上,您需要告诉 ERB 将输出缓冲区存储在变量中。
脚本最终看起来像这样:
require 'erb'
def listing(title, attributes={})
concat %Q{
<example id='#{attributes[:id]}'>
<programlisting>
<title>#{title}</title>}
yield
concat %Q{
</programlisting>
</example>
}
end
def concat(string)
@output.concat(string)
end
example = %Q{<% listing "db/migrate/[date]_create_purchases.rb", :id => "ch01_292" do %>
<![CDATA[class CreatePurchases < ActiveRecord::Migration
def change
create_table :purchases do |t|
t.string :name
t.float :cost
t.timestamps
end
end
end]]>
<% end %>}
chapter = ERB.new(example, nil, nil, "@output")
p chapter.result(binding)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1753 次 |
| 最近记录: |