If I understood correctly, something like this could work for you:
# template.rb
this template contains:
<%= array.inspect %>
<%
first = array.shift
if first
%>
<%= first %>,
<%= ERB.new(File.read("template.erb"), 0, "",
"result_#{array.length}").result(binding) %>
<%
end
%>
and something else.
1.9.2p290 :041 > array = [1,2,3,4]; ERB.new(File.read("template.erb"),
0, "", "result_#{array.length}").result(binding)
=> "this template contains:\n[1, 2, 3, 4]\n\n1,\nthis template
contains:\n[2, 3, 4]\n\n2,\nthis template contains:\n[3,
4]\n\n3,\nthis template contains:\n[4]\n\n4,\nthis template
contains:\n\n\nand something else.\n\nand something else.\n\nand
something else.\n\nand something else.\n\nand something else."
You are doing too much file reading here because you reread the
template file for each value. That's not necessary since we can use
parameter binding.
The trick is to create a unique temporary variable for the ouput of
each iteration. If not, erb will overwrite the result of each
iteration.
I think the trick lies in getting bindings properly by nesting them
properly. My first naive approaches did not work because variables
were overwritten.
I don't know how you represent your nested objects. In this example I
created an array through which I recursively generate a template.
Same here:
#!/opt/bin/ruby19
require 'erb'
def rt(s)
e = ERB.new(s)
recursive = lambda {|a, level| e.result(binding)}
end
arr = [
1,
2,
[3],
[4, [5]],
6
]
e = rt %Q{
<%= ' ' * level %>open level=<%= level %>
<%
if Enumerable === a
a.each do |x|
%><%= recursive[x, level + 1] %><%
end
else
%><%= ' ' * level %><%= a %><%
end
%>
<%= ' ' * level %>close level=<%= level %>
}
p arr
puts e[arr, 0]
Kind regards
robert
···
On Wed, Jun 20, 2012 at 1:53 PM, Jesús Gabriel y Galán <jgabrielygalan@gmail.com> wrote:
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/