On Wed, Jun 20, 2012 at 3:22 AM, Todd W. [email protected] wrote:
My code generator will generate Java nested classes. The problem is the
level of nesting can’t be determined statically. So, the ideal case is I
define a Java class template in ERB, which accepts binding variables as
input
parameter, and in the template, it can “call” itself with new bindings.
Just like what does recursive function do.
I’m not sure if i can achieve this with “invoke arbitrary code”. For
example, can I invoke the template itself with new bindings in the
template? Could you give me an example? Thanks!
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.”
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 don’t know how you represent your nested objects. In this example I
created an array through which I recursively generate a template.
I hope this gives you some ideas.
Jesus.