Search code examples
rubymetaprogrammingtemplate-engineerboutput-buffering

About using method "print" etc. in ERB for metaprogramming


I am using ERB via console for metaprogramming (for math software). For example, I have file test.erb containing

text line before ruby
<%=  'via <%='  %>
<%  print 'print'  %>
<%  puts  'puts'   %>
text line after ruby

When I parse it by $ erb test.erb, I get the following output

printputs
text line before ruby
via <%=


text line after ruby

I am not surprised by it, but wonder if there is a good way to catch output of print method and put it at the place where it is called in the ERB template?

text line before ruby
via <%=
print
puts
text line after ruby

Imagine that I have a complex construction, where I would prefer to print instead of collecting output in a string inside <%= %>.


Update

Just to illustrate the answer of Brian:

text line before ruby
<%= '<%=' %>
% print 'print'
% puts 'puts'
% E = _erbout
% E << '_erbout'+"\n"
text line after ruby

Parsing the file $ erb test.erb:

printputs
text line before ruby
<%=
_erbout
text line after ruby

Solution

  • Not certain if this helps in your particular case, but consider looking at some examples using the _erbout method

    text line before ruby
    <%=  'via <%='  %>
    <% _erbout << 'print' %>
    <% _erbout << 'puts'  %>
    text line after ruby
    

    Hope this gets you somewhere.