views:

38

answers:

2

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
+1  A: 

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.

Brian
Thanks, Brian! It seems to work for me.
Andrey
A: 

As an option, one can redefine Kernel#p method:

file: p_for_erb.rb

module Kernel
  alias :p_super :p

  def p *args
    if args.empty?
      @@_erbout
    elsif args.first.class == Hash
      @@_erbout = args.first[:init]
    else
      args.each { |a| @@_erbout << a }
    end
  end
end

...and then do similar to this:

file: mytest.erb

text before ruby
% require 'p_for_erb'
% p init: _erbout # to initialize class variable @@_erbout
% p "my p output"

Command $ erb mytest.erb produces

text before ruby
my p output
Andrey