Compiles ERB templates into Ruby code; the compiled code produces the template result when evaluated. ERB::Compiler provides hooks to define how generated output is handled.

Internally ERB does something like this to generate the code returned by ERB#src:

compiler ='<>')
compiler.pre_cmd    = ["_erbout=+''"]
compiler.put_cmd    = "_erbout.<<"
compiler.insert_cmd = "_erbout.<<"
compiler.post_cmd   = ["_erbout"]

code, enc = compiler.compile("Got <%= obj %>!\n")
puts code


_erbout=+''; _erbout.<< "Got ".freeze; _erbout.<<(( obj ).to_s); _erbout.<< "!\n".freeze; _erbout

By default the output is sent to the print method. For example:

compiler ='<>')
code, enc = compiler.compile("Got <%= obj %>!\n")
puts code


print "Got ".freeze; print(( obj ).to_s); print "!\n".freeze


The compiled code can be used in any context where the names in the code correctly resolve. Using the last example, each of these print ‘Got It!’

Evaluate using a variable:

obj = 'It'
eval code

Evaluate using an input:

mod =
mod.module_eval %{
  def get(obj)
extend mod

Evaluate using an accessor:

klass = Object
klass.class_eval %{
  attr_accessor :obj
  def initialize(obj)
    @obj = obj
  def get_it

Good! See also ERB#def_method, ERB#def_module, and ERB#def_class.


SimpleScanner2 = SimpleScanner # :nodoc:


[RW] content

A buffered text in #compile

[RW] post_cmd

An array of commands appended to compiled code

[RW] pre_cmd

An array of commands prepended to compiled code

[RW] insert_cmd

The command to handle text that is inserted prior to a newline

[RW] put_cmd

The command to handle text that ends with a newline

[R] trim_mode
[R] percent
Show files where this class is defined (1 file)
Register or log in to add new notes.