Erubis Users' Guide

release: 2.6.6
last update: $Date$

release: 2.6.6

Preface

Erubis is an implementation of eRuby. It has the following features.

Erubis is implemented in pure Ruby. It requires Ruby 1.8 or higher. Erubis now supports Ruby 1.9.

Table of Contents



Installation


Tutorial

Basic Example

Here is a basic example of Erubis.

example1.eruby
<ul>
  <% for item in list %>
  <li><%= item %></li>
  <% end %>
  <%# here is ignored because starting with '#' %>
</ul>
example1.rb
require 'erubis'
input = File.read('example1.eruby')
eruby = Erubis::Eruby.new(input)    # create Eruby object

puts "---------- script source ---"
puts eruby.src                      # print script source

puts "---------- result ----------"
list = ['aaa', 'bbb', 'ccc']
puts eruby.result(binding())        # get result
## or puts eruby.result(:list=>list)  # or pass Hash instead of Binding

## # or
## eruby = Erubis::Eruby.new
## input = File.read('example1.eruby')
## src = eruby.convert(input)
## eval src
output
$ ruby example1.rb
---------- script source ---
_buf = ''; _buf << '<ul>
';   for item in list 
 _buf << '  <li>'; _buf << ( item ).to_s; _buf << '</li>
';   end 

 _buf << '</ul>
';
_buf.to_s
---------- result ----------
<ul>
  <li>aaa</li>
  <li>bbb</li>
  <li>ccc</li>
</ul>

Erubis has command 'erubis'. Command-line option '-x' shows the compiled source code of eRuby script.

example of command-line option '-x'
$ erubis -x example1.eruby
_buf = ''; _buf << '<ul>
';   for item in list 
 _buf << '  <li>'; _buf << ( item ).to_s; _buf << '</li>
';   end 

 _buf << '</ul>
';
_buf.to_s

Trimming Spaces

Erubis deletes spaces around '<% %>' automatically, while it leaves spaces around '<%= %>'.

example2.eruby
<ul>
  <% for item in list %>      # trimmed
  <li>
    <%= item %>               # not trimmed
  </li>
  <% end %>                   # trimmed
</ul>
compiled source code
$ erubis -x example2.eruby
_buf = ''; _buf << '<ul>
';   for item in list 
 _buf << '  <li>
    '; _buf << ( item ).to_s; _buf << '
'; _buf << '  </li>
';   end 
 _buf << '</ul>
';
_buf.to_s

If you want leave spaces around '<% %>', add command-line property '--trim=false'.

compiled source code with command-line property '--trim=false'
$ erubis -x --trim=false example2.eruby
_buf = ''; _buf << '<ul>
'; _buf << '  '; for item in list ; _buf << '
'; _buf << '  <li>
    '; _buf << ( item ).to_s; _buf << '
'; _buf << '  </li>
'; _buf << '  '; end ; _buf << '
'; _buf << '</ul>
';
_buf.to_s

Or add option :trim=>false to Erubis::Eruby.new().

example2.rb
require 'erubis'
input = File.read('example2.eruby')
eruby = Erubis::Eruby.new(input, :trim=>false)

puts "----- script source ---"
puts eruby.src                            # print script source

puts "----- result ----------"
list = ['aaa', 'bbb', 'ccc']
puts eruby.result(binding())              # get result
output
$ ruby example2.rb
----- script source ---
_buf = ''; _buf << '<ul>
'; _buf << '  '; for item in list ; _buf << '
'; _buf << '  <li>
    '; _buf << ( item ).to_s; _buf << '
'; _buf << '  </li>
'; _buf << '  '; end ; _buf << '
'; _buf << '</ul>
';
_buf.to_s
----- result ----------
<ul>
  
  <li>
    aaa
  </li>
  
  <li>
    bbb
  </li>
  
  <li>
    ccc
  </li>
  
</ul>

Escape

Erubis has ability to escape (sanitize) expression. Erubis::Eruby class act as the following:

Erubis::EscapedEruby(*1) class handle '<%= %>' as escaped and '<%== %>' as not escaped. It means that using Erubis::EscapedEruby you can escape expression by default. Also Erubis::XmlEruby class (which is equivalent to Erubis::EscapedEruby) is provided for compatibility with Erubis 1.1.

example3.eruby
<% for item in list %>
  <p><%= item %></p>
  <p><%== item %></p>
  <p><%=== item %></p>

<% end %>
example3.rb
require 'erubis'
input = File.read('example3.eruby')
eruby = Erubis::EscapedEruby.new(input)    # or Erubis::XmlEruby

puts "----- script source ---"
puts eruby.src                             # print script source

puts "----- result ----------"
list = ['<aaa>', 'b&b', '"ccc"']
puts eruby.result(binding())               # get result
output
$ ruby example3.rb 2> stderr.log
----- script source ---
_buf = ''; for item in list 
 _buf << '  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
  <p>'; _buf << ( item ).to_s; _buf << '</p>
  <p>'; $stderr.puts("*** debug: item=#{(item).inspect}"); _buf << '</p>

'; end 
_buf.to_s
----- result ----------
  <p>&lt;aaa&gt;</p>
  <p><aaa></p>
  <p></p>

  <p>b&amp;b</p>
  <p>b&b</p>
  <p></p>

  <p>&quot;ccc&quot;</p>
  <p>"ccc"</p>
  <p></p>

$ cat stderr.log
*** debug: item="<aaa>"
*** debug: item="b&b"
*** debug: item="\"ccc\""

The command-line option '-e' will do the same action as Erubis::EscapedEruby. This option is available for any language.

$ erubis -l ruby -e example3.eruby
_buf = ''; for item in list 
 _buf << '  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
  <p>'; _buf << ( item ).to_s; _buf << '</p>
  <p>'; $stderr.puts("*** debug: item=#{(item).inspect}"); _buf << '</p>

'; end 
_buf.to_s

Escaping function (default 'Erubis::XmlHelper.escape_xml()') can be changed by command-line property '--escapefunc=xxx' or by overriding Erubis::Eruby#escaped_expr() in subclass.

example to override Erubis::Eruby#escaped_expr()
class CGIEruby < Erubis::Eruby
  def escaped_expr(code)
    return "CGI.escapeHTML((#{code.strip}).to_s)"
    #return "h(#{code.strip})"
  end
end

class LatexEruby < Erubi::Eruby
  def escaped_expr(code)
    return "(#{code}).gsub(/[%\\]/,'\\\\\&')"
  end
end
(*1)
Erubis::EscapedEruby class includes Erubis::EscapeEnhancer which swtches the action of '<%= %>' and '<%== %>'.

Embedded Pattern

You can change embedded pattern '<% %>' to another by command-line option '-p' or option ':pattern=>...' of Erubis::Eruby.new().

example4.eruby
<!--% for item in list %-->
  <p><!--%= item %--></p>
<!--% end %-->
compiled source code with command-line option '-p'
$ erubis -x -p '<!--% %-->' example4.eruby
_buf = ''; for item in list 
 _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
'; end 
_buf.to_s
example4.rb
require 'erubis'
input = File.read('example4.eruby')
eruby = Erubis::Eruby.new(input, :pattern=>'<!--% %-->')
                                      # or '<(?:!--)?% %(?:--)?>'

puts "---------- script source ---"
puts eruby.src                            # print script source

puts "---------- result ----------"
list = ['aaa', 'bbb', 'ccc']
puts eruby.result(binding())              # get result
output
$ ruby example4.rb
---------- script source ---
_buf = ''; for item in list 
 _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
'; end 
_buf.to_s
---------- result ----------
  <p>aaa</p>
  <p>bbb</p>
  <p>ccc</p>

It is able to specify regular expression with :pattern option. Notice that you must use '(?: )' instead of '( )' for grouping. For example, '<(!--)?% %(--)?>' will not work while '<(?:!--)?% %(?:--)?>' will work.


Context Object

Context object is a set of data which are used in eRuby script. Using context object makes clear which data to be used. In Erubis, Hash object and Erubis::Context object are available as context object.

Context data can be accessible via instance variables in eRuby script.

example5.eruby
<span><%= @val %></span>
<ul>
 <% for item in @list %>
  <li><%= item %></li>
 <% end %>
</ul>
example5.rb
require 'erubis'
input = File.read('example5.eruby')
eruby = Erubis::Eruby.new(input)      # create Eruby object

## create context object
## (key means var name, which may be string or symbol.)
context = {
  :val   => 'Erubis Example',
  'list' => ['aaa', 'bbb', 'ccc'],
}
## or
# context = Erubis::Context.new()
# context['val'] = 'Erubis Example'
# context[:list] = ['aaa', 'bbb', 'ccc'],

puts eruby.evaluate(context)         # get result
output
$ ruby example5.rb
<span>Erubis Example</span>
<ul>
  <li>aaa</li>
  <li>bbb</li>
  <li>ccc</li>
</ul>

The difference between Erubis#result(binding) and Erubis#evaluate(context) is that the former invokes 'eval @src, binding' and the latter invokes 'context.instance_eval @src'. This means that data is passed into eRuby script via local variables when Eruby::binding() is called, or passed via instance variables when Eruby::evaluate() is called.

Here is the definition of Erubis#result() and Erubis#evaluate().

definition of result(binding) and evaluate(context)
def result(_binding=TOPLEVEL_BINDING)
  if _binding.is_a?(Hash)
    # load hash data as local variable
    _h = _binding
    _binding = binding()
    eval _h.collect{|k,v| "#{k} = _h[#{k.inspect}];"}.join, _binding
  end
  return eval(@src, _binding)
end

def evaluate(_context=Erubis::Context.new)
  if _context.is_a?(Hash)
    # convert hash object to Context object
    _hash = _context
    _context = Erubis::Context.new
    _hash.each {|k, v| _context[k] = v }
  end
  return _context.instance_eval(@src)
end

instance_eval() is defined at Object class so it is able to use any object as a context object as well as Hash or Erubis::Context.

example6.rb
class MyData
  attr_accessor :val, :list
end

## any object can be a context object
mydata = MyData.new
mydata.val = 'Erubis Example'
mydata.list = ['aaa', 'bbb', 'ccc']

require 'erubis'
eruby = Erubis::Eruby.new(File.read('example5.eruby'))
puts eruby.evaluate(mydata)
output
$ ruby example6.rb
<span>Erubis Example</span>
<ul>
  <li>aaa</li>
  <li>bbb</li>
  <li>ccc</li>
</ul>

It is recommended to use 'Erubis::Eruby#evaluate(context)' rather than 'Erubis::Eruby#result(binding())' because the latter has some problems. See evaluate(context) v.s. result(binding) section for details.


Context Data File

Command-line option '-f' specifies context data file. Erubis load context data file and use it as context data. Context data file can be YAML file ('*.yaml' or '*.yml') or Ruby script ('*.rb').

example7.eruby
<h1><%= @title %></h1>
<ul>
 <% for user in @users %>
  <li>
    <a href="mailto:<%= user['mail']%>"><%= user['name'] %></a>
  </li>
 <% end %>
</ul>
context.yaml
title: Users List
users:
  - name:  foo
    mail:  foo@mail.com
  - name:  bar
    mail:  bar@mail.net
  - name:  baz
    mail:  baz@mail.org
context.rb
@title = 'Users List'
@users = [
   { 'name'=>'foo', 'mail'=>'foo@mail.com' },
   { 'name'=>'bar', 'mail'=>'bar@mail.net' },
   { 'name'=>'baz', 'mail'=>'baz@mail.org' },
]
example of command-line option '-f'
$ erubis -f context.yaml example7.eruby
<h1>Users List</h1>
<ul>
  <li>
    <a href="mailto:foo@mail.com">foo</a>
  </li>
  <li>
    <a href="mailto:bar@mail.net">bar</a>
  </li>
  <li>
    <a href="mailto:baz@mail.org">baz</a>
  </li>
</ul>
$ erubis -f context.rb example7.eruby
<h1>Users List</h1>
<ul>
  <li>
    <a href="mailto:foo@mail.com">foo</a>
  </li>
  <li>
    <a href="mailto:bar@mail.net">bar</a>
  </li>
  <li>
    <a href="mailto:baz@mail.org">baz</a>
  </li>
</ul>

Command-line option '-S' converts keys of mapping in YAML data file from string into symbol. Command-line option '-B' invokes 'Erubis::Eruby#result(binding())' instead of 'Erubis::Eruby#evaluate(context)'.


Context Data String

Command-line option '-c str' enables you to specify context data in command-line. str can be YAML flow-style or Ruby code.

example8.eruby
<h1><%= @title %></h1>
<ul>
<% for item in @list %>
 <li><%= item %></li>
<% end %>
</ul>
example of YAML flow style
$ erubis -c '{title: Example, list: [AAA, BBB, CCC]}' example8.eruby
<h1>Example</h1>
<ul>
 <li>AAA</li>
 <li>BBB</li>
 <li>CCC</li>
</ul>
example of Ruby code
$ erubis -c '@title="Example"; @list=%w[AAA BBB CCC]' example8.eruby
<h1>Example</h1>
<ul>
 <li>AAA</li>
 <li>BBB</li>
 <li>CCC</li>
</ul>

Preamble and Postamble

The first line ('_buf = '';') in the compiled source code is called preamble and the last line ('_buf.to_s') is called postamble.

Command-line option '-b' skips the output of preamble and postamble.

example9.eruby
<% for item in @list %>
 <b><%= item %></b>
<% end %>
compiled source code with and without command-line option '-b'
$ erubis -x example9.eruby
_buf = ''; for item in @list 
 _buf << ' <b>'; _buf << ( item ).to_s; _buf << '</b>
'; end 
_buf.to_s
$ erubis -x -b example9.eruby
 for item in @list 
 _buf << ' <b>'; _buf << ( item ).to_s; _buf << '</b>
'; end 

Erubis::Eruby.new option ':preamble=>false' and ':postamble=>false' also suppress output of preamble or postamle.

example9.rb
require 'erubis'
input = File.read('example9.eruby')
eruby1 = Erubis::Eruby.new(input)
eruby2 = Erubis::Eruby.new(input, :preamble=>false, :postamble=>false)

puts eruby1.src   # print preamble and postamble
puts "--------------"
puts eruby2.src   # don't print preamble and postamble
output
$ ruby example9.rb
_buf = ''; for item in @list 
 _buf << ' <b>'; _buf << ( item ).to_s; _buf << '</b>
'; end 
_buf.to_s
--------------
 for item in @list 
 _buf << ' <b>'; _buf << ( item ).to_s; _buf << '</b>
'; end 

Processing Instruction (PI) Converter

Erubis can parse Processing Instructions (PI) as embedded pattern.

This is more useful than basic embedded pattern ('<% ... >') because PI doesn't break XML or HTML at all. For example the following XHTML file is well-formed and HTML validator got no errors on this example.

example10.xhtml
<?xml version="1.0" ?>
<?rb
  lang = 'en'
  list = ['<aaa>', 'b&b', '"ccc"']
?>
<html lang="@!{lang}@">
 <body>
  <ul>
  <?rb for item in list ?>
   <li>@{item}@</li>
  <?rb end ?>
  </ul>
 </body>
</html>

If the command-line property '--pi=name' is specified, erubis command parses input with PI converter. If name is omitted then the following name is used according to '-l lang'.

'-l' option PI name
-l ruby <?rb ... ?>
-l php <?php ... ?>
-l perl <?perl ... ?>
-l java <?java ... ?>
-l javascript <?js ... ?>
-l scheme <?scheme ... ?>
output
$ erubis -x --pi example10.xhtml
_buf = ''; _buf << '<?xml version="1.0" ?>
';
  lang = 'en'
  list = ['<aaa>', 'b&b', '"ccc"']

 _buf << '<html lang="'; _buf << (lang).to_s; _buf << '">
 <body>
  <ul>
';   for item in list 
 _buf << '   <li>'; _buf << Erubis::XmlHelper.escape_xml(item); _buf << '</li>
';   end 
 _buf << '  </ul>
 </body>
</html>
';
_buf.to_s

Expression character can be changeable by command-line property '--embchar=char. Default is '@'.

Use Erubis::PI::Eruby instead of Erubis::Eruby if you want to use PI as embedded pattern.

example10.rb
require 'erubis'
input = File.read('example10.xhtml')
eruby = Erubis::PI::Eruby.new(input)
print eruby.src
output
$ ruby example10.rb
_buf = ''; _buf << '<?xml version="1.0" ?>
';
  lang = 'en'
  list = ['<aaa>', 'b&b', '"ccc"']

 _buf << '<html lang="'; _buf << (lang).to_s; _buf << '">
 <body>
  <ul>
';   for item in list 
 _buf << '   <li>'; _buf << Erubis::XmlHelper.escape_xml(item); _buf << '</li>
';   end 
 _buf << '  </ul>
 </body>
</html>
';
_buf.to_s

(experimental) Erubis supports '<%= ... %>' pattern with PI pattern.

example of Rails view template
<table>
  <tr>
<?rb for item in @list ?>
    <td>@{item.id}@</td>
    <td>@{item.name}@</td>
    <td>
       <%= link_to 'Destroy', {:action=>'destroy', :id=>item.id},
                       :confirm=>'Are you OK?' %>
    </td>
<?rb end ?>
  </tr>
</table>

Retrieve Ruby Code

Similar to '-x', ommand-line option '-X' shows converted Ruby source code. The difference between '-x' and 'X' is that the former converts text part but the latter ignores it. It means that you can retrieve Ruby code from eRuby script by '-X' option.

For example, see the following eRuby script. This is some complex, so it is difficult to grasp the program code.

example11.rhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <body>
    <h3>List</h3>
    <% if @list.nil? || @list.empty? %>
    <p>not found.</p>
    <% else %>
    <table>
      <tbody>
        <% @list.each_with_index do |item, i| %>
        <tr bgcolor="<%= i % 2 == 0 ? '#FCC' : '#CCF' %>">
          <td><%= item %></td>
        </tr>
        <% end %>
      </tbody>
    </table>
    <% end %>
  </body>
</html>

Command-line option '-X' extracts only the ruby code from eRuby script.

result
$ erubis -X example11.rhtml
_buf = '';





     if @list.nil? || @list.empty? 

     else 


         @list.each_with_index do |item, i| 
                      _buf << ( i % 2 == 0 ? '#FCC' : '#CCF' ).to_s;
               _buf << ( item ).to_s;

         end 


     end 


_buf.to_s

Command-line option '-C' (cmpact) deletes empty lines.

result
$ erubis -XC example11.rhtml
_buf = '';
     if @list.nil? || @list.empty? 
     else 
         @list.each_with_index do |item, i| 
                      _buf << ( i % 2 == 0 ? '#FCC' : '#CCF' ).to_s;
               _buf << ( item ).to_s;
         end 
     end 
_buf.to_s

Option '-U' (unique) converts empty lines into a line.

result
$ erubis -XU example11.rhtml
_buf = '';

     if @list.nil? || @list.empty? 

     else 

         @list.each_with_index do |item, i| 
                      _buf << ( i % 2 == 0 ? '#FCC' : '#CCF' ).to_s;
               _buf << ( item ).to_s;

         end 

     end 

_buf.to_s

Option '-N' (number) adds line number. It is available with '-C' or '-U'.

result
$ erubis -XNU example11.rhtml
    1:  _buf = '';

    7:       if @list.nil? || @list.empty? 

    9:       else 

   12:           @list.each_with_index do |item, i| 
   13:                        _buf << ( i % 2 == 0 ? '#FCC' : '#CCF' ).to_s;
   14:                 _buf << ( item ).to_s;

   16:           end 

   19:       end 

   22:  _buf.to_s

Command-line option '-X' is available with PHP script.

example11.php
<?xml version="1.0"?>
<html>
  <body>
    <h3>List</h3>
    <?php if (!$list) { ?>
    <p>not found.</p>
    <?php } else { ?>
    <table>
      <tbody>
        <?php $i = 0; ?>
        <?php foreach ($list as $item) { ?>
        <tr bgcolor="<?php echo ++$i % 2 == 1 ? '#FCC' : '#CCF'; ?>">
          <td><?php echo $item; ?></td>
        </tr>
        <?php } ?>
      </tbody>
    </table>
    <?php } ?>
  </body>
</html>
result
$ erubis -XNU -l php --pi=php --trim=false example11.php

    5:      <?php if (!$list) { ?>

    7:      <?php } else { ?>

   10:          <?php $i = 0; ?>
   11:          <?php foreach ($list as $item) { ?>
   12:                       <?php echo ++$i % 2 == 1 ? '#FCC' : '#CCF'; ?>
   13:                <?php echo $item; ?>

   15:          <?php } ?>

   18:      <?php } ?>



Enhancer

Enhancer is a module to add a certain feature into Erubis::Eruby class. Enhancer may be language-independent or only for Erubis::Eruby class.

To use enhancers, define subclass and include them. The folloing is an example to use EscapeEnhancer, PercentLineEnhancer, and BiPatternEnhancer.

class MyEruby < Erubis::Eruby
  include EscapeEnhancer
  include PercentLineEnhancer
  include BiPatternEnhancer
end

You can specify enhancers in command-line with option '-E'. The following is an example to use some enhancers in command-line.

$ erubis -xE Escape,PercentLine,BiPattern example.eruby

The following is the list of enhancers.

EscapeEnhander (language-independent)
Switch '<%= %>' to escaped and '<%== %>' to unescaped.
StdoutEnhancer (only for Eruby)
Use $stdout instead of array buffer.
PrintOutEnhancer (only for Eruby)
Use "print(...)" statement insead of "_buf << ...".
PrintEnabledEnhancer (only for Eruby)
Enable to use print() in '<% ... %>'.
ArrayEnhancer (only for Eruby)
Return array of string instead of returning string.
ArrayBufferEnhancer (only for Eruby)
Use array buffer. It is a little slower than StringBufferEnhancer.
StringBufferEnhancer (only for Eruby)
Use string buffer. This is included in Erubis::Eruby by default.
ErboutEnhancer (only for Eruby)
Set '_erbout = _buf = "";' to be compatible with ERB.
NoTextEnhancer (language-independent)
Print embedded code only and ignore normal text.
NoCodeEnhancer (language-independent)
Print normal text only and ignore code.
SimplifyEnhancer (language-independent)
Make compile faster but don't trim spaces around '<% %>'.
BiPatternEnhancer (language-independent)
[experimental] Enable to use another embedded pattern with '<% %>'.
PercentLineEnhancer (language-independent)
Regard lines starting with '%' as Ruby code. This is for compatibility with eruby and ERB.
HeaderFooterEnhancer (language-independent)
[experimental] Enable you to add header and footer in eRuby script.
InterpolationEnhancer (only for Eruby)
[experimental] convert '<p><%= text %></p>' into '_buf << %Q`<p>#{text}</p>`'.
DeleteIndentEnhancer (language-independent)
[experimental] delete indentation of HTML file and eliminate page size.

If you required 'erubis/engine/enhanced', Eruby subclasses which include each enhancers are defined. For example, class BiPatternEruby includes BiPatternEnhancer.

EscapeEnhancer

EscapeEnhancer switches '<%= ... %>' to escaped and '<%== ... %>' to unescaped.

example.eruby
<div>
<% for item in list %>
  <p><%= item %></p>
  <p><%== item %></p>
<% end %>
</div>
compiled source code
$ erubis -xE Escape example.eruby
_buf = ''; _buf << '<div>
'; for item in list 
 _buf << '  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
  <p>'; _buf << ( item ).to_s; _buf << '</p>
'; end 
 _buf << '</div>
';
_buf.to_s

EscapeEnhancer is language-independent.


StdoutEnhancer

StdoutEnhancer use $sdtdout instead of array buffer. Therefore, you can use 'print' statement in embedded ruby code.

compiled source code
$ erubis -xE Stdout example.eruby
_buf = $stdout; _buf << '<div>
'; for item in list 
 _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
'; end 
 _buf << '</div>
';
''

StdoutEnhancer is only for Eruby.


PrintOutEnhancer

PrintOutEnhancer makes compiled source code to use 'print(...)' instead of '_buf << ...'.

compiled source code
$ erubis -xE PrintOut example.eruby
 print '<div>
'; for item in list 
 print '  <p>'; print(( item ).to_s); print '</p>
  <p>'; print Erubis::XmlHelper.escape_xml( item ); print '</p>
'; end 
 print '</div>
';

PrintOutEnhancer is only for Eruby.


PrintEnabledEnhancer

PrintEnabledEnhancer enables you to use print() method in '<% ... %>'.

printenabled-example.eruby
<% for item in @list %>
  <b><% print item %></b>
<% end %>
printenabled-example.rb
require 'erubis'
class PrintEnabledEruby < Erubis::Eruby
  include Erubis::PrintEnabledEnhancer
end
input = File.read('printenabled-example.eruby')
eruby = PrintEnabledEruby.new(input)
list = ['aaa', 'bbb', 'ccc']
print eruby.evaluate(:list=>list)
output result
$ ruby printenabled-example.rb
  <b>aaa</b>
  <b>bbb</b>
  <b>ccc</b>

Notice to use Eruby#evaluate() and not to use Eruby#result(), because print() method in '<% ... %>' invokes not Kernel#print() but PrintEnabledEnhancer#print().

PrintEnabledEnhancer is only for Eruby.


ArrayEnhancer

ArrayEnhancer makes Eruby to return an array of strings.

compiled source code
$ erubis -xE Array example.eruby
_buf = []; _buf << '<div>
'; for item in list 
 _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
'; end 
 _buf << '</div>
';
_buf

ArrayEnhancer is only for Eruby.


ArrayBufferEnhancer

ArrayBufferEnhancer makes Eruby to use array buffer. Array buffer is a litte slower than String buffer.

ArrayBufferEnhancer is only for Eruby.

compiled source code
$ erubis -xE ArrayBuffer example.eruby
_buf = []; _buf << '<div>
'; for item in list 
 _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
'; end 
 _buf << '</div>
';
_buf.join

StringBufferEnhancer

StringBufferEnhancer makes Eruby to use string buffer. String buffer is a little faster than array buffer. Erubis::Eruby includes this enhancer by default.

compiled source code
$ erubis -xE StringBuffer example.eruby
_buf = ''; _buf << '<div>
'; for item in list 
 _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
'; end 
 _buf << '</div>
';
_buf.to_s

StringBufferEnhancer is only for Eruby.


ErboutEnhancer

ErboutEnhancer makes Eruby to be compatible with ERB. This is useful especially for Ruby on Rails.

compiled source code
$ erubis -xE Erbout example.eruby
_erbout = _buf = ''; _buf << '<div>
'; for item in list 
 _buf << '  <p>'; _buf << ( item ).to_s; _buf << '</p>
  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
'; end 
 _buf << '</div>
';
_buf.to_s

ErboutEnhancer is only for Eruby.


NoTextEnhancer

NoTextEnhancer suppress output of text and prints only embedded code. This is useful especially when debugging a complex eRuby script.

notext-example.eruby
<h3>List</h3>
<% if !@list || @list.empty? %>
<p>not found.</p>
<% else %>
<table>
  <tbody>
    <% @list.each_with_index do |item, i| %>
    <tr bgcolor="<%= i%2 == 0 ? '#FFCCCC' : '#CCCCFF' %>">
      <td><%= item %></td>
    </tr>
    <% end %>
  </tbody>
</table>
<% end %>
output example of NoTextEnhancer
$ erubis -xE NoText notext-example.eruby
_buf = '';
 if !@list || @list.empty? 

 else 


     @list.each_with_index do |item, i| 
                  _buf << ( i%2 == 0 ? '#FFCCCC' : '#CCCCFF' ).to_s;
           _buf << ( item ).to_s;

     end 


 end 
_buf.to_s

NoTextEnhancer is language-independent. It is useful even if you are PHP user, see this section.


NoCodeEnhancer

NoCodeEnhancer suppress output of embedded code and prints only normal text. This is useful especially when validating HTML tags.

nocode-example.eruby
<h3>List</h3>
<% if !@list || @list.empty? %>
<p>not found.</p>
<% else %>
<table>
  <tbody>
    <% @list.each_with_index do |item, i| %>
    <tr bgcolor="<%= i%2 == 0 ? '#FFCCCC' : '#CCCCFF' %>">
      <td><%= item %></td>
    </tr>
    <% end %>
  </tbody>
</table>
<% end %>
output example of NoCodeEnhancer
$ erubis -xE NoCode notext-example.eruby
<h3>List</h3>

<p>not found.</p>

<table>
  <tbody>

    <tr bgcolor="">
      <td></td>
    </tr>

  </tbody>
</table>

NoCodeEnhancer is language-independent. It is useful even if you are PHP user, see this section.


SimplifyEnhancer

SimplifyEnhancer makes compiling a little faster but don't trim spaces around '<% %>'.

compiled source code
$ erubis -xE Simplify example.eruby
_buf = ''; _buf << '<div>
'; for item in list ; _buf << '
  <p>'; _buf << ( item ).to_s; _buf << '</p>
  <p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
'; end ; _buf << '
</div>
';
_buf.to_s

SimplifyEnhancer is language-independent.


BiPatternEnhancer

BiPatternEnhancer enables to use another embedded pattern with '<% %>'. By Default, '[= ... =]' is available for expression. You can specify pattern by :bipattern property.

bipattern-example.rhtml
<% for item in list %>
  <b>[= item =]</b>
  <b>[== item =]</b>
<% end %>
compiled source code
$ erubis -xE BiPattern bipattern-example.rhtml
_buf = ''; for item in list 
 _buf << '  <b>'; _buf << ( item ).to_s; _buf << '</b>
  <b>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</b>
'; end 
_buf.to_s

BiPatternEnhancer is language-independent.


PercentLineEnhancer

PercentLineEnhancer regards lines starting with '%' as Ruby code. This is for compatibility with eruby and ERB.

percentline-example.rhtml
% for item in list
  <b><%= item %></b>
% end
%% lines with '%%'
compiled source code
$ erubis -xE PercentLine percentline-example.rhtml
_buf = ''; for item in list
 _buf << '  <b>'; _buf << ( item ).to_s; _buf << '</b>
'; end
 _buf << '% lines with \'%%\'
';
_buf.to_s

PercentLineEnhancer is language-independent.


HeaderFooterEnhancer

[experimental]

HeaderFooterEnhancer enables you to add header and footer in eRuby script.

headerfooter-example.eruby
<!--#header:
def list_items(items)
#-->
<% for item in items %>
  <b><%= item %></b>
<% end %>
<!--#footer:
end
#-->
compiled source code
$ erubis -xE HeaderFooter headerfooter-example.eruby

def list_items(items)

_buf = ''; for item in items 
 _buf << '  <b>'; _buf << ( item ).to_s; _buf << '</b>
'; end 
_buf.to_s

end

Compare to the following:

normal-eruby-test.eruby
<%
def list_items(items)
%>
<% for item in items %>
<li><%= item %></li>
<% end %>
<%
end
%>
compiled source code
$ erubis -x normal-eruby-test.eruby
_buf = '';
def list_items(items)

 for item in items 
 _buf << '<li>'; _buf << ( item ).to_s; _buf << '</li>
'; end 

end

_buf.to_s

Header and footer can be in any position in eRuby script, that is, header is no need to be in the head of eRuby script.

headerfooter-example2.rhtml
<?xml version="1.0"?>
<html>
<!--#header:
def page(list)
#-->
 :
<!--#footer:
end
#-->
</html>
compiled source code
$ erubis -xE HeaderFooter headerfooter-example2.rhtml

def page(list)

_buf = ''; _buf << '<?xml version="1.0"?>
<html>
'; _buf << ' :
'; _buf << '</html>
';
_buf.to_s

end

HeaderFooterEnhancer is experimental and is language-independent.


InterpolationEnhancer

[experimental]

InterpolationEnhancer converts "<h1><%= title %></h1>" into "_buf << %Q`<h1>#{ title }</h1>`". This makes Eruby a litter faster because method call of String#<< are eliminated by expression interpolations.

InterpolationEnhancer elmininates method call of String#<<.
## Assume that input is '<a href="<%=url%>"><%=name%></a>'.
## Eruby convert input into the following code.  String#<< is called 5 times.
_buf << '<a href="'; _buf << (url).to_s; _buf << '">'; _buf << (name).to_s; _buf << '</a>';

## If InterpolationEnhancer is used, String#<< is called only once.
_buf << %Q`<a href="#{url}">#{name}</a>`;
compiled source code
$ erubis -xE Interpolation example.eruby
_buf = ''; _buf << %Q`<div>\n`
 for item in list 
 _buf << %Q`  <p>#{ item }</p>
  <p>#{Erubis::XmlHelper.escape_xml( item )}</p>\n`
 end 
 _buf << %Q`</div>\n`
_buf.to_s

Erubis provides Erubis::FastEruby class which includes InterpolationEnhancer. You can use Erubis::FastEruby class instead of Erubis::Eruby class.

InterpolationEnhancer is only for Eruby.


DeleteIndentEnhancer

[experimental] DeleteIndentEnhancer deletes indentation of HTML file.

compiled source code
$ erubis -xE DeleteIndent example.eruby
_buf = ''; _buf << '<div>
'; for item in list 
 _buf << '<p>'; _buf << ( item ).to_s; _buf << '</p>
<p>'; _buf << Erubis::XmlHelper.escape_xml( item ); _buf << '</p>
'; end 
 _buf << '</div>
';
_buf.to_s

Notice that DeleteIndentEnhancer isn't intelligent. It deletes indentations even if they are in <PRE></PRE>.

DeleteIndentEnhancer is language-independent.



Multi-Language Support

Erubis supports the following languages(*2):

(*2)
If you need template engine in pure PHP/Perl/JavaScript, try Tenjin (http://www.kuwata-lab.com/tenjin/). Tenjin is a very fast and full-featured template engine implemented in pure PHP/Perl/JavaScript.

PHP

example.ephp
<?xml version="1.0"?>
<html>
 <body>
  <p>Hello <%= $user %>!</p>
  <table>
   <tbody>
    <% $i = 0; %>
    <% foreach ($list as $item) { %>
    <%   $i++; %>
    <tr bgcolor="<%= $i % 2 == 0 ? '#FFCCCC' : '#CCCCFF' %>">
     <td><%= $i %></td>
     <td><%== $item %></td>
    </tr>
    <% } %>
   </tbody>
  </table>
 </body>
</html>
compiled source code
$ erubis -l php example.ephp
<<?php ?>?xml version="1.0"?>
<html>
 <body>
  <p>Hello <?php echo $user; ?>!</p>
  <table>
   <tbody>
<?php     $i = 0; ?>
<?php     foreach ($list as $item) { ?>
<?php       $i++; ?>
    <tr bgcolor="<?php echo $i % 2 == 0 ? '#FFCCCC' : '#CCCCFF'; ?>">
     <td><?php echo $i; ?></td>
     <td><?php echo htmlspecialchars($item); ?></td>
    </tr>
<?php     } ?>
   </tbody>
  </table>
 </body>
</html>

C

example.ec
<%
#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;

%>
<html>
 <body>
  <p>Hello <%= "%s", argv[0] %>!</p>
  <table>
   <tbody>
    <% for (i = 1; i < argc; i++) { %>
    <tr bgcolor="<%= i % 2 == 0 ? "#FFCCCC" : "#CCCCFF" %>">
      <td><%= "%d", i %></td>
      <td><%= "%s", argv[i] %></td>
    </tr>
    <% } %>
   </tbody>
  </table>
 </body>
</html>
<%
    return 0; 
}
%>
compiled source code
$ erubis -l c example.ec
#line 1 "example.ec"

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;


fputs("<html>\n"
      " <body>\n"
      "  <p>Hello ", stdout); fprintf(stdout, "%s", argv[0]); fputs("!</p>\n"
      "  <table>\n"
      "   <tbody>\n", stdout);
     for (i = 1; i < argc; i++) { 
fputs("    <tr bgcolor=\"", stdout); fprintf(stdout, i % 2 == 0 ? "#FFCCCC" : "#CCCCFF"); fputs("\">\n"
      "      <td>", stdout); fprintf(stdout, "%d", i); fputs("</td>\n"
      "      <td>", stdout); fprintf(stdout, "%s", argv[i]); fputs("</td>\n"
      "    </tr>\n", stdout);
     } 
fputs("   </tbody>\n"
      "  </table>\n"
      " </body>\n"
      "</html>\n", stdout);

    return 0; 
}


Java

Example.ejava
<%
import java.util.*;

public class Example {
  private String user;
  private String[] list;
  public example(String user, String[] list) {
    this.user = user;
    this.list = list;
  }

  public String view() {
    StringBuffer _buf = new StringBuffer();
%>
<html>
 <body>
  <p>Hello <%= user %>!</p>
  <table>
   <tbody>
    <% for (int i = 0; i < list.length; i++) { %>
    <tr bgcolor="<%= i % 2 == 0 ? "#FFCCCC" : "#CCCCFF" %>">
     <td><%= i + 1 %></td>
     <td><%== list[i] %></td>
    </tr>
    <% } %>
   </tbody>
  </table>
 <body>
</html>
<%
    return _buf.toString();
  }

  public static void main(String[] args) {
    String[] list = { "<aaa>", "b&b", "\"ccc\"" };
    Example ex = Example.new("Erubis", list);
    System.out.print(ex.view());
  }

  public static String escape(String s) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < s.length(); i++) {
      char ch = s.charAt(i);
      switch (ch) {
      case '<':   sb.append("&lt;"); break;
      case '>':   sb.append("&gt;"); break;
      case '&':   sb.append("&amp;"); break;
      case '"':   sb.append("&quot;"); break;
      default:    sb.append(ch);
      }
    }
    return sb.toString();
  }
}
%>
compiled source code
$ erubis -b -l java example.ejava

import java.util.*;

public class Example {
  private String user;
  private String[] list;
  public example(String user, String[] list) {
    this.user = user;
    this.list = list;
  }

  public String view() {
    StringBuffer _buf = new StringBuffer();

_buf.append("<html>\n"
          + " <body>\n"
          + "  <p>Hello "); _buf.append(user); _buf.append("!</p>\n"
          + "  <table>\n"
          + "   <tbody>\n");
     for (int i = 0; i < list.length; i++) { 
_buf.append("    <tr bgcolor=\""); _buf.append(i % 2 == 0 ? "#FFCCCC" : "#CCCCFF"); _buf.append("\">\n"
          + "     <td>"); _buf.append(i + 1); _buf.append("</td>\n"
          + "     <td>"); _buf.append(escape(list[i])); _buf.append("</td>\n"
          + "    </tr>\n");
     } 
_buf.append("   </tbody>\n"
          + "  </table>\n"
          + " <body>\n"
          + "</html>\n");

    return _buf.toString();
  }

  public static void main(String[] args) {
    String[] list = { "<aaa>", "b&b", "\"ccc\"" };
    Example ex = Example.new("Erubis", list);
    System.out.print(ex.view());
  }

  public static String escape(String s) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < s.length(); i++) {
      char ch = s.charAt(i);
      switch (ch) {
      case '<':   sb.append("&lt;"); break;
      case '>':   sb.append("&gt;"); break;
      case '&':   sb.append("&amp;"); break;
      case '"':   sb.append("&quot;"); break;
      default:    sb.append(ch);
      }
    }
    return sb.toString();
  }
}


Scheme

example.escheme
<html>
 <body>
<%
(let ((user "Erubis")
      (items '("<aaa>" "b&b" "\"ccc\""))
      (i 0))
 %>
  <p>Hello <%= user %>!</p>
  <table>
<%
  (for-each
   (lambda (item)
     (set! i (+ i 1))
 %>
   <tr bgcolor="<%= (if (= (modulo i 2) 0) "#FFCCCC" "#CCCCFF") %>">
    <td><%= i %></td>
    <td><%= item %></td>
   </tr>
<%
   ) ; lambda end
   items) ; for-each end
 %>
  </table>
<%
) ; let end
%>
 </body>
</html>
compiled source code
$ erubis -l scheme example.escheme
(let ((_buf '())) (define (_add x) (set! _buf (cons x _buf))) (_add "<html>
 <body>\n")

(let ((user "Erubis")
      (items '("<aaa>" "b&b" "\"ccc\""))
      (i 0))
 
(_add "  <p>Hello ")(_add user)(_add "!</p>
  <table>\n")

  (for-each
   (lambda (item)
     (set! i (+ i 1))
 
(_add "   <tr bgcolor=\"")(_add (if (= (modulo i 2) 0) "#FFCCCC" "#CCCCFF"))(_add "\">
    <td>")(_add i)(_add "</td>
    <td>")(_add item)(_add "</td>
   </tr>\n")

   ) ; lambda end
   items) ; for-each end
 
(_add "  </table>\n")

) ; let end

(_add " </body>
</html>\n")
  (reverse _buf))
compiled source code (with --func=display property)
$ erubis -l scheme --func=display example.escheme
(display "<html>
 <body>\n")

(let ((user "Erubis")
      (items '("<aaa>" "b&b" "\"ccc\""))
      (i 0))
 
(display "  <p>Hello ")(display user)(display "!</p>
  <table>\n")

  (for-each
   (lambda (item)
     (set! i (+ i 1))
 
(display "   <tr bgcolor=\"")(display (if (= (modulo i 2) 0) "#FFCCCC" "#CCCCFF"))(display "\">
    <td>")(display i)(display "</td>
    <td>")(display item)(display "</td>
   </tr>\n")

   ) ; lambda end
   items) ; for-each end
 
(display "  </table>\n")

) ; let end

(display " </body>
</html>\n")

Perl

example.eprl
<%
   my $user = 'Erubis';
   my @list = ('<aaa>', 'b&b', '"ccc"');
%>
<html>
 <body>
  <p>Hello <%= $user %>!</p>
  <table>
   <% $i = 0; %>
   <% for $item (@list) { %>
   <tr bgcolor=<%= ++$i % 2 == 0 ? '#FFCCCC' : '#CCCCFF' %>">
    <td><%= $i %></td>
    <td><%= $item %></td>
   </tr>
   <% } %>
  </table>
 </body>
</html>
compiled source code
$ erubis -l perl example.eperl
use HTML::Entities; 
   my $user = 'Erubis';
   my @list = ('<aaa>', 'b&b', '"ccc"');

print('<html>
 <body>
  <p>Hello '); print($user); print('!</p>
  <table>
');     $i = 0; 
    for $item (@list) { 
print('   <tr bgcolor='); print(++$i % 2 == 0 ? '#FFCCCC' : '#CCCCFF'); print('">
    <td>'); print($i); print('</td>
    <td>'); print($item); print('</td>
   </tr>
');     } 
print('  </table>
 </body>
</html>
'); 

JavaScript

example.ejs
<%
   var user = 'Erubis';
   var list = ['<aaa>', 'b&b', '"ccc"'];
 %>
<html>
 <body>
  <p>Hello <%= user %>!</p>
  <table>
   <tbody>
    <% var i; %>
    <% for (i = 0; i < list.length; i++) { %>
    <tr bgcolor="<%= i % 2 == 0 ? '#FFCCCC' : '#CCCCFF' %>">
     <td><%= i + 1 %></td>
     <td><%= list[i] %></td>
    </tr>
    <% } %>
   </tbody>
  </table>
 </body>
</html>
compiled source code
$ erubis -l js example.ejs
var _buf = [];
   var user = 'Erubis';
   var list = ['<aaa>', 'b&b', '"ccc"'];
 
_buf.push("<html>\n\
 <body>\n\
  <p>Hello "); _buf.push(user); _buf.push("!</p>\n\
  <table>\n\
   <tbody>\n");
     var i; 
     for (i = 0; i < list.length; i++) { 
_buf.push("    <tr bgcolor=\""); _buf.push(i % 2 == 0 ? '#FFCCCC' : '#CCCCFF'); _buf.push("\">\n\
     <td>"); _buf.push(i + 1); _buf.push("</td>\n\
     <td>"); _buf.push(list[i]); _buf.push("</td>\n\
    </tr>\n");
     } 
_buf.push("   </tbody>\n\
  </table>\n\
 </body>\n\
</html>\n");
document.write(_buf.join(""));

If command-line option '--docwrite=false' is specified, '_buf.join("");' is used instead of 'document.write(_buf.join(""));'. This is useful when passing converted source code to eval() function in JavaScript.

You can pass :docwrite=>false to Erubis::Ejavascript.new() in your Ruby script.

s = File.read('example.jshtml')
engine = Erubis::Ejavascript.new(s, :docwrite=>false)

If you want to specify any JavaScript code, use '--postamble=...'.

Notice that default value of 'docwrite' property will be false in the future release.



Ruby on Rails Support

Erubis supports Ruby on Rails. This section describes how to use Erubis with Ruby on Rails.

Settings

Add the following code to your 'config/environment.rb' and restart web server. This replaces ERB in Rails by Erubis entirely.

config/environment.rb
require 'erubis/helpers/rails_helper'
#Erubis::Helpers::RailsHelper.engine_class = Erubis::Eruby # or Erubis::FastEruby
#Erubis::Helpers::RailsHelper.init_properties = {}
#Erubis::Helpers::RailsHelper.show_src = nil
#Erubis::Helpers::RailsHelper.preprocessing = false

Options:

Erubis::Helpers::RailsHelper.engine_class (=Erubis::Eruby)

Erubis engine class (default Erubis::Eruby).

Erubis::Helpers::RailsHelper.init_properties (={})

Optional arguments for Erubis::Eruby#initialize() method (default {}).

Erubis::Helpers::RailsHelper.show_src (=nil)

Whether to print converted Ruby code into log file. If true, Erubis prints coverted code into log file. If false, Erubis doesn't. If nil, Erubis prints when ENV['RAILS_ENV'] == 'development'. Default is nil.

Erubis::Helpers::RailsHelper.preprocessing (=false)

Enable preprocessing if true (default false).


Preprosessing

Erubis supports preprocessing of template files. Preprocessing make your Ruby on Rails application about 20-40 percent faster. To enable preprocessing, set Erubis::Helpers::RailsHelper.preprocessing to true in your 'environment.rb' file.

For example, assume the following template. This is slow because link_to() method is called every time when template is rendered.

<%= link_to 'Create', :action=>'create' %>

The following is faster than the above, but not flexible because url is fixed.

<a href="/users/create">Create</a>

Preprocessing solves this problem. If you use '[%= %]' instead of '<%= %>', preprocessor evaluate it only once when template is loaded.

[%= link_to 'Create', :action=>'create'%]

The above is evaluated by preprocessor and replaced to the following code automatically.

<a href="/users/create">Create</a>

Notice that this is done only once when template file is loaded. It means that link_to() method is not called when template is rendered.

If link_to() method have variable arguments, use _?() helper method.

<% for user in @users %>
[%= link_to _?('user.name'), :action=>'show', :id=>_?('user.id') %]
<% end %>

The above is evaluated by preprocessor when template is loaded and expanded into the following code. This will be much faster because link_to() method is not called when rendering.

<% for user in @users %>
<a href="/users/show/<%=user.id%>"><%=user.name%></a>
<% end %>

Preprocessing statement ([% %]) is also available as well as preprocessing expression ([%= %]).

<select name="state">
  <option value="">-</option>
[% for code in states.keys.sort %]
  <option value="[%= code %]">[%= states[code] %]</option>
[% end %]
</select>

The above will be evaluated by preprocessor and expanded into the following when template is loaded. In the result, rendering speed will be much faster because for-loop is not executed when rendering.

<select name="state">
  <option value="">-</option>
  <option value="AK">Alaska</option>
  <option value="AL">Alabama</option>
  <option value="AR">Arkansas</option>
  <option value="AS">American Samoa</option>
  <option value="AZ">Arizona</option>
  <option value="CA">California</option>
  <option value="CO">Colorado</option>
   ....
</select>

Notice that it is not recommended to use preprocessing with tag helpers, because tag helpers generate different html code when form parameter has errors or not.

Helper methods of Ruby on Rails are divided into two groups.

In Ruby on Rails 2.0, _?('user_id') is OK but _?('user.id') is NG because the latter contains period ('.') character.

<!-- NG in Rails 2.0, because _?('') contains period -->
[%= link_to 'Edit', edit_user_path(_?('@user.id')) %]
[%= link_to 'Show', @user %]
[%= link_to 'Delete', @user, :confirm=>'OK?', :method=>:delete %]

<!-- OK in Rails 2.0 -->
<%= user_id = @user.id %>
[%= link_to 'Edit', edit_user_path(_?('user_id')) %]
[%= link_to 'Show', :action=>'show', :id=>_?('user_id') %]
[%= link_to 'Delete', {:action=>'destroy', :id=>_?('user_id')},
                      {:confirm=>'OK?', :method=>:delete} %]

Form Helpers for Preprocessing

(Experimental)

Erubis provides form helper methods for preprocessing. These are defined in 'erubis/helpers/rails_form_helper.rb'. If you want to use it, require it and include Erubis::Helpers::RailsFormHelper in 'app/helpers/applition_helper.rb'

app/helpers/xxx_helper.rb
require 'erubis/helpers/rails_form_helper'
module ApplicationHelper
  include Erubis::Helpers::RailsFormHelper
end

Form helper methods defined in Erubis::Helpers::RailsFormHelper are named as 'pp_xxxx' ('pp' represents preprocessing).

Assume the following view template:

_form.rhtml
 <p>
  Name: <%= text_field :user, :name %>
 </p>
 <p>
  Name: [%= pp_text_field :user, :name %]
 </p>

Erubis preprocessor converts it to the following eRuby string:

preprocessed
 <p>
  Name: <%= text_field :user, :name %>
 </p>
 <p>
  Name: <input id="stock_name" name="stock[name]" size="30" type="text" value="<%=h @stock.name%>" />
 </p>

Erubis converts it to the following Ruby code:

Ruby code
 _buf << ' <p>
  Name: '; _buf << ( text_field :stock, :name ).to_s; _buf << '
'; _buf << ' </p>
 <p>
  Name: <input id="stock_name" name="stock[name]" size="30" type="text" value="'; _buf << (h @stock.name).to_s; _buf << '" />
 </p>
';

The above Ruby code shows that text_field() is called everytime when rendering, but pp_text_field() is called only once when template is loaded. This means that pp_text_field() with preprocessing makes view layer very fast.

Module Erubis::Helpers::RailsFormHelper defines the following form helper methods.

Notice that pp_form_for() is not provided.

CAUTION: These are experimental and may not work in Ruby on Rails 2.0.


Others



Other Topics

'<%= =%>' and '<%= -%>'

Since 2.6.0, '<%= -%>' remove tail spaces and newline. This is for compatibiliy with ERB when trim mode is '-'. '<%= =%>' also removes tail spaces and newlines, and this is Erubis-original enhancement (cooler than '<%= -%>', isn't it?).

tailnewline.rhtml
<div>
<%= @var -%>          # or <%= @var =%>
</div>
result (version 2.5.0):
$ erubis -c '{var: "AAA\n"}' tailnewline.rhtml
<div>
AAA

</div>
result (version 2.6.0):
$ erubis -c '{var: "AAA\n"}' tailnewline.rhtml
<div>
AAA
</div>

'<%% %>' and '<%%= %>'

Since 2.6.0, '<%% %>' and '<%%= %>' are converted into '<% %>' and '<%= %>' respectively. This is for compatibility with ERB.

doublepercent.rhtml:
<ul>
<%% for item in @list %>
  <li><%%= item %></li>
<%% end %>
</ul>
result:
$ erubis doublepercent.rhtml
<ul>
<% for item in @list %>
  <li><%= item %></li>
<% end %>
</ul>

evaluate(context) v.s. result(binding)

It is recommended to use 'Erubis::Eruby#evaluate(context)' instead of 'Erubis::Eruby#result(binding)' because Ruby's Binding object has some problems.

The following example shows that assignment of some values into variable 'x' in templates affect to local variable 'x' in main program unintendedly.

template1.rhtml (intended to be passed 'items' from main program)
<% for x in items %>
item = <%= x %>
<% end %>
** debug: local variables=<%= local_variables().inspect() %>
main_program1.rb (intended to pass 'items' to template)
require 'erubis'
eruby = Erubis::Eruby.new(File.read('template1.rhtml'))
items = ['foo', 'bar', 'baz']
x = 1
## local variable 'x' and 'eruby' are passed to template as well as 'items'!
print eruby.result(binding())    
## local variable 'x' is changed unintendedly because it is changed in template!
puts "** debug: x=#{x.inspect}"  #=> "baz"
Result:
$ ruby main_program1.rb
item = foo
item = bar
item = baz
** debug: local variables=["eruby", "items", "x", "_buf"]
** debug: x="baz"

This problem is caused because Ruby's Binding class is poor to use in template engine. Binding class should support the following features.

b = Binding.new     # create empty Binding object
b['x'] = 1          # set local variables using binding object

But the above features are not implemented in Ruby.

A pragmatic solution is to use 'Erubis::Eruby#evaluate(context)' instead of 'Erubis::Eruby#result(binding)'. 'evaluate(context)' uses Erubis::Context object and instance variables instead of Binding object and local variables.

template2.rhtml (intended to be passed '@items' from main program)
<% for x in @items %>
item = <%= x %>
<% end %>
** debug: local variables=<%= local_variables().inspect() %>
main_program2.rb (intended to pass '@items' to template)
require 'erubis'
eruby = Erubis::Eruby.new(File.read('template2.rhtml'))
items = ['foo', 'bar', 'baz']
x = 1
## only 'items' are passed to template
print eruby.evaluate(:items=>items)    
## local variable 'x' is not changed!
puts "** debug: x=#{x.inspect}"  #=> 1
Result:
$ ruby main_program2.rb
item = foo
item = bar
item = baz
** debug: local variables=["_context", "x", "_buf"]
** debug: x=1

Class Erubis::FastEruby

[experimental]

Erubis provides Erubis::FastEruby class which includes InterpolationEnhancer and works faster than Erubis::Eruby class. If you desire more speed, try Erubis::FastEruby class.

File 'fasteruby.rhtml':
<html>
  <body>
    <h1><%== @title %></h1>
    <table>
<% i = 0 %>
<% for item in @list %>
<%   i += 1 %>
      <tr>
        <td><%= i %></td>
        <td><%== item %></td>
      </tr>
<% end %>
    </table>
  </body>
</html>
File 'fasteruby.rb':
require 'erubis'
input = File.read('fasteruby.rhtml')
eruby = Erubis::FastEruby.new(input)    # create Eruby object

puts "---------- script source ---"
puts eruby.src

puts "---------- result ----------"
context = { :title=>'Example', :list=>['aaa', 'bbb', 'ccc'] }
output = eruby.evaluate(context)
print output
output
$ ruby fasteruby.rb
---------- script source ---
_buf = ''; _buf << %Q`<html>
  <body>
    <h1>#{Erubis::XmlHelper.escape_xml( @title )}</h1>
    <table>\n`
 i = 0 
 for item in @list 
   i += 1 
 _buf << %Q`      <tr>
        <td>#{ i }</td>
        <td>#{Erubis::XmlHelper.escape_xml( item )}</td>
      </tr>\n`
 end 
 _buf << %Q`    </table>
  </body>
</html>\n`
_buf.to_s
---------- result ----------
<html>
  <body>
    <h1>Example</h1>
    <table>
      <tr>
        <td>1</td>
        <td>aaa</td>
      </tr>
      <tr>
        <td>2</td>
        <td>bbb</td>
      </tr>
      <tr>
        <td>3</td>
        <td>ccc</td>
      </tr>
    </table>
  </body>
</html>

Syntax Checking

Command-line option '-z' checks syntax. It is similar to 'erubis -x file.rhtml | ruby -wc', but it can take several file names.

example of command-line option '-z'
$ erubis -z app/views/*/*.rhtml
Syntax OK

File Caching

Erubis::Eruby.load_file(filename) convert file into Ruby script and return Eruby object. In addition, it caches converted Ruby script into cache file (filename + '.cache') if cache file is old or not exist. If cache file exists and is newer than eruby file, Erubis::Eruby.load_file() loads cache file.

example of Erubis::Eruby.load_file()
require 'erubis'
filename = 'example.rhtml'
eruby = Erubis::Eruby.load_file(filename)
cachename = filename + '.cache'
if test(?f, cachename)
  puts "*** cache file '#{cachename}' created."
end

Since 2.6.0, it is able to specify cache filename.

specify cache filename.
filename = 'example.rhtml'
eruby = Erubis::Eruby.load_file(filename, :cachename=>filename+'.cache')

Caching makes Erubis about 40-50 percent faster than no-caching. See benchmark for details.


Erubis::TinyEruby class

Erubis::TinyEruby class in 'erubis/tiny.rb' is the smallest implementation of eRuby. If you don't need any enhancements of Erubis and only require simple eRuby implementation, try Erubis::TinyEruby class.


NoTextEnhancer and NoCodeEnhancer in PHP

NoTextEnhancer and NoCodEnahncer are quite useful not only for eRuby but also for PHP. The former "drops" HTML text and show up embedded Ruby/PHP code and the latter drops embedded Ruby/PHP code and leave HTML text.

For example, see the following PHP script.

notext-example.php
<html>
  <body>
    <h3>List</h3>
    <?php if (!$list || count($list) == 0) { ?>
    <p>not found.</p>
    <?php } else { ?>
    <table>
      <tbody>
        <?php $i = 0; ?>
        <?php foreach ($list as $item) { ?>
        <tr bgcolor="<?php echo ++$i % 2 == 1 ? '#FFCCCC' : '#CCCCFF'; ?>">
          <td><?php echo $item; ?></td>
        </tr>
        <?php } ?>
      </tbody>
    </table>
    <?php } ?>
  </body>
</html>

This is complex because PHP code and HTML document are mixed. NoTextEnhancer can separate PHP code from HTML document.

example of using NoTextEnhancer with PHP file
$ erubis -l php --pi=php -N -E NoText --trim=false notext-example.php
    1:  
    2:  
    3:  
    4:      <?php if (!$list || count($list) == 0) { ?>
    5:  
    6:      <?php } else { ?>
    7:  
    8:  
    9:          <?php $i = 0; ?>
   10:          <?php foreach ($list as $item) { ?>
   11:                       <?php echo ++$i % 2 == 1 ? '#FFCCCC' : '#CCCCFF'; ?>
   12:                <?php echo $item; ?>
   13:  
   14:          <?php } ?>
   15:  
   16:  
   17:      <?php } ?>
   18:  
   19:  

In the same way, NoCodeEnhancer can extract HTML tags.

example of using NoCodeEnhancer with PHP file
$ erubis -l php --pi=php -N -E NoCode --trim=false notext-example.php
    1:  <html>
    2:    <body>
    3:      <h3>List</h3>
    4:      
    5:      <p>not found.</p>
    6:      
    7:      <table>
    8:        <tbody>
    9:          
   10:          
   11:          <tr bgcolor="">
   12:            <td></td>
   13:          </tr>
   14:          
   15:        </tbody>
   16:      </table>
   17:      
   18:    </body>
   19:  </html>

Helper Class for mod_ruby

Thanks Andrew R Jackson, he developed 'erubis-run.rb' which enables you to use Erubis with mod_ruby.

  1. Copy 'erubis-2.6.6/contrib/erubis-run.rb' to the 'RUBYLIBDIR/apache' directory (for example '/usr/local/lib/ruby/1.8/apache') which contains 'ruby-run.rb', 'eruby-run.rb', and so on.
    $ cd erubis-2.6.6/
    $ sudo copy contrib/erubis-run.rb /usr/local/lib/ruby/1.8/apache/
    
  2. Add the following example to your 'httpd.conf' (for example '/usr/local/apache2/conf/httpd.conf')
    LoadModule ruby_module modules/mod_ruby.so
    <IfModule mod_ruby.c>
      RubyRequire apache/ruby-run
      RubyRequire apache/eruby-run
      RubyRequire apache/erubis-run
      <Location /erubis>
        SetHandler ruby-object
        RubyHandler Apache::ErubisRun.instance
      </Location>
      <Files *.rhtml>
        SetHandler ruby-object
        RubyHandler Apache::ErubisRun.instance
      </Files>
    </IfModule>
    
  3. Restart Apache web server.
    $ sudo /usr/local/apache2/bin/apachectl stop
    $ sudo /usr/local/apache2/bin/apachectl start
    
  4. Create *.rhtml file, for example:
    <html>
     <body>
      Now is <%= Time.now %>
      Erubis version is <%= Erubis::VERSION %>
     </body>
    </html>
    
  5. Change mode of your directory to be writable by web server process.
    $ cd /usr/local/apache2/htdocs/erubis
    $ sudo chgrp daemon .
    $ sudo chmod 775 .
    
  6. Access the *.rhtml file and you'll get the web page.

You must set your directories to be writable by web server process, because Apache::ErubisRun calls Erubis::Eruby.load_file() internally which creates cache files in the same directory in which '*.rhtml' file exists.


Define method

Erubis::Eruby#def_method() defines instance method or singleton method.

require 'erubis'
s = "hello <%= name %>"
eruby = Erubis::Eruby.new(s)
filename = 'hello.rhtml'

## define instance method to Dummy class (or module)
class Dummy; end
eruby.def_method(Dummy, 'render(name)', filename)  # filename is optional
p Dummy.new.render('world')    #=> "hello world"

## define singleton method to dummy object
obj = Object.new
eruby.def_method(obj, 'render(name)', filename)    # filename is optional
p obj.render('world')          #=> "hello world"

Benchmark

A benchmark script is included in Erubis package at 'erubis-2.6.6/benchark/' directory. Here is an example result of benchmark.

MacOS X 10.4 Tiger, Intel CoreDuo 1.83GHz, Ruby1.8.6, eruby1.0.5, gcc4.0.1
$ cd erubis-2.6.6/benchmark/
$ ruby bench.rb -n 10000 -m execute
*** ntimes=10000, testmode=execute
                                    user     system      total        real
eruby                          12.720000   0.240000  12.960000 ( 12.971888)
ERB                            36.760000   0.350000  37.110000 ( 37.112019)
ERB(cached)                    11.990000   0.440000  12.430000 ( 12.430375)
Erubis::Eruby                  10.840000   0.300000  11.140000 ( 11.144426)
Erubis::Eruby(cached)           7.540000   0.410000   7.950000 (  7.969305)
Erubis::FastEruby              10.440000   0.300000  10.740000 ( 10.737808)
Erubis::FastEruby(cached)       6.940000   0.410000   7.350000 (  7.353666)
Erubis::TinyEruby               9.550000   0.290000   9.840000 (  9.851729)
Erubis::ArrayBufferEruby       11.010000   0.300000  11.310000 ( 11.314339)
Erubis::PrintOutEruby          11.640000   0.290000  11.930000 ( 11.942141)
Erubis::StdoutEruby            11.590000   0.300000  11.890000 ( 11.886512)

This shows that...

Escaping HTML characters (such as '< > & "') makes Erubis more faster than eruby and ERB, because Erubis::XmlHelper#escape_xml() works faster than CGI.escapeHTML() and ERB::Util#h(). The following shows that Erubis runs more than 40 percent (when no-cached) or 90 percent (when cached) faster than eruby if HTML characters are escaped.

When escaping HTML characters with option '-e'
$ ruby bench.rb -n 10000 -m execute -ep
*** ntimes=10000, testmode=execute
                                    user     system      total        real
eruby                          21.700000   0.290000  21.990000 ( 22.050687)
ERB                            45.140000   0.390000  45.530000 ( 45.536976)
ERB(cached)                    20.340000   0.470000  20.810000 ( 20.822653)
Erubis::Eruby                  14.830000   0.310000  15.140000 ( 15.147930)
Erubis::Eruby(cached)          11.090000   0.420000  11.510000 ( 11.514954)
Erubis::FastEruby              14.850000   0.310000  15.160000 ( 15.172499)
Erubis::FastEruby(cached)      10.970000   0.430000  11.400000 ( 11.399605)
Erubis::ArrayBufferEruby       14.970000   0.300000  15.270000 ( 15.281061)
Erubis::PrintOutEruby          15.780000   0.300000  16.080000 ( 16.088289)
Erubis::StdoutEruby            15.840000   0.310000  16.150000 ( 16.235338)


Command Reference

Usage

erubis [..options..] [file ...]


Options

-h, --help
Help.
-v
Release version.
-x
Show compiled source.
-X
Show compiled source but only Ruby code. This is equivarent to '-E NoText'.
-N
Numbering: add line numbers. (for '-x/-X')
-U
Unique mode: zip empty lines into a line. (for '-x/-X')
-C
Compact: remove empty lines. (for '-x/-X')
-b
Body only: no preamble nor postamble. (for '-x/-X') This is equivarent to '--preamble=false --postamble=false'.
-z
Syntax checking.
-e
Escape. This is equivarent to '-E Escape'.
-p pattern
Embedded pattern (default '<% %>'). This is equivarent to '--pattern=pattern'.
-l lang
Language name. This option makes erubis command to compile script but no execute.
-E enhacers
Enhancer name (Escape, PercentLine, ...). It is able to specify several enhancer name separating with ',' (ex. -f Escape,PercentLine,HeaderFooter).
-I path
Require library path ($:). It is able to specify several paths separating with ',' (ex. -f path1,path2,path3).
-K kanji
Kanji code (euc, sjis, utf8, or none) (default none).
-f datafile
Context data file in YAML format ('*.yaml', '*.yml') or Ruby script ('*.rb'). It is able to specify several filenames separating with ',' (ex. -f file1,file2,file3).
-c context
Context data string in YAML inline style or Ruby code.
-T
Don't expand tab characters in YAML file.
-S
Convert mapping key from string to symbol in YAML file.
-B
invoke Eruby#result() instead of Eruby#evaluate()
--pi[=name]
parse '<?name ... ?>' instead of '<% ... %>'
--trim=false
No trimming spaces around '<% %>'.

Properties

Some Eruby classes can take optional properties to change it's compile option. For example, property '--indent=" "' may change indentation of compiled source code. Try 'erubis -h' for details.