Class: Mime::ERBComponent

Inherits:
Component show all
Defined in:
lib/mime-components/extensions/erb.rb

Overview

A component wrapped around a compiled Erubi template.

Instance Attribute Summary

Attributes inherited from Component

#name

Instance Method Summary collapse

Methods inherited from Component

attr_true?, #render

Constructor Details

#initialize(name, template) ⇒ ERBComponent

Create a new Mime component from an Erubi template. XML arguments will be passed to this template as an instance variable named ‘@args`, and variables will be set as instance varibles (for example, ’:my_variable’ would be accessible as ‘@my_variable’).



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/mime-components/extensions/erb.rb', line 12

def initialize(name, template)
   # pre-compile template
   @erubi_engine = Erubi::Engine.new(template, freeze: true, escape: true)
   # execute template in a new context with few variables
   super(name) do |args, vars|
      # george is a sandbox instance that can only access variables and arguments
      # passed to the template by this component.
      george = Object.new
      # pass arguments
      george.instance_variable_set(:@args, args)
      # pass global variables
      vars.each { |var| george.instance_variable_set(:"@#{var[0]}", var[1]) }
      # pass instance variables
      instance_variables.each { |var| george.instance_variable_set(var, instance_variable_get(var)) }
      # evaluate template as george :)
      george.instance_eval(@erubi_engine.src)
   end
end