class SandboxedErb::Template
This class represents a template which can be compiled then run multiple times.
When declaring a template, pass an array of Mixin classes to the contructor to allow the template access to the Mixin methods.
Example
module ExampleHelper def format_date(date, format) if format == :short_date date.strftime("%d %b %Y %H:%M") else "unknown format: #{format}" end end def current_time DateTime.now end end template = SandboxedErb::Template.new([ExampleHelper]) #the template will now have access to the format_date() and current_time() helper function template.compile('the date = <%=format_date(current_time, :short_date)%>')
Public Class Methods
minins is an array of helper classes which expose methods to the template
# File lib/sandboxed_erb/template.rb, line 53 def initialize(mixins = []) @mixins = mixins.collect { |clz| "include #{clz.name}"}.join("\n") end
Public Instance Methods
compile the template
if the template does not compile, false is returned and get_error
should be called to get the compile error.
# File lib/sandboxed_erb/template.rb, line 60 def compile(str_template) erb_template = compile_erb_template(str_template) return false if erb_template.nil? #we now have a normal compile erb template (which is just ruby code) sandboxed_compiled_template = sandbox_code(erb_template) puts sandboxed_compiled_template if $DEBUG return false if sandboxed_compiled_template.nil? @clazz_name = "SandboxedErb::TClass#{self.object_id}" @file_name = "tclass_#{self.object_id}" clazz_str = <<-EOF class #{@clazz_name} < SandboxedErb::TemplateBase #{@mixins} def run_internal() #{sandboxed_compiled_template} end end #{@clazz_name}.new EOF begin @template_runner = eval(clazz_str, nil, @file_name) rescue Exception=>e @error = "Invalid code generated: #{e.message}" return false end true end
# File lib/sandboxed_erb/template.rb, line 164 def get_error @error end
run a compiled template
-
context: A map of context objects that will be available to helper functions and instance variables, and available to sandboxed objects through the set_sandbox_context callback.
-
locals: A map of local objects that will be available to the template, and available to sandboxed objects through the set_sandbox_context callback as the :locals entry.
If the template runs successfully, the geneated content is returned. If an error occures, nil is returned and get_error
should be called to get the error information.
# File lib/sandboxed_erb/template.rb, line 98 def run(context, locals) begin @template_runner.run(context, locals) rescue Exception=>e @error = e.message nil end end