ERB::Compiler
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 = ERB::Compiler.new('<>') compiler.pre_cmd = ["_erbout=String.new"] compiler.put_cmd = "_erbout.concat" compiler.insert_cmd = "_erbout.concat" compiler.post_cmd = ["_erbout"] code, enc = compiler.compile("Got <%= obj %>!\n") puts code
Generates:
#coding:UTF-8 _erbout=String.new; _erbout.concat "Got "; _erbout.concat(( obj ).to_s); _erbout.concat "!\n"; _erbout
By default the output is sent to the print method. For example:
compiler = ERB::Compiler.new('<>') code, enc = compiler.compile("Got <%= obj %>!\n") puts code
Generates:
#coding:UTF-8 print "Got "; print(( obj ).to_s); print "!\n"
Evaluation
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 = Module.new mod.module_eval %{ def get(obj) #{code} end } extend mod get('It')
Evaluate using an accessor:
klass = Class.new Object klass.class_eval %{ attr_accessor :obj def initialize(obj) @obj = obj end def get_it #{code} end } klass.new('It').get_it
Good! See also ERB#def_method, ERB#def_module, and ERB#def_class.