require 'erb' ## # Caches compiled ERB templates. # # Usage: # # c = ERB::Cached.new # c.add_erb :test, "The value of x is <%= x %>" # p c.test(:x => 5) class ERB::Cached ## # Add cached ERB +template+ as +name+. # # You can call it later with class.+name+(:arg1 => val1, ...) def add_erb(name, template) ERB.new(template).def_method self.class, "run_#{name}" end ## # Dispatches to the compiled ERB template +action+, setting variables from # +options+. def method_missing(action, options = {}) super unless self.respond_to? "run_#{action}" options.each do |attr, value| self.class.send :attr_accessor, attr unless self.respond_to? attr self.send "#{attr}=", value end return self.send("run_#{action}") end end if __FILE__ == $0 then c = ERB::Cached.new c.add_erb :test, "The value of x is <%= x %>" p c.test(:x => 5) end