Class: Template

Inherits:
Object
  • Object
show all
Defined in:
lib/template.rb,
lib/template/node.rb,
lib/template/parser.rb,
lib/template/node/part.rb,
lib/template/node/template.rb,
lib/template/node/code_part.rb,
lib/template/node/text_part.rb,
lib/template/parser/template.rb

Defined Under Namespace

Classes: Node, Parser

Constant Summary collapse

DEFAULT_TIMEOUT =
10
Version =
Gem::Version.new("0.5.2")

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, io: StringIO.new, timeout: DEFAULT_TIMEOUT, ruby: {}) ⇒ Template

Returns a new instance of Template.



4
5
6
7
8
9
10
11
# File 'lib/template.rb', line 4

def initialize(input, io: StringIO.new, timeout: DEFAULT_TIMEOUT, ruby: {})
  @input = input
  @parsed =
    Timeout.timeout(timeout) { ::Template::Parser.parse(@input).to_raw }
  @io = io
  @timeout = timeout || DEFAULT_TIMEOUT
  @ruby = ::Code::Ruby.to_code(ruby || {})
end

Class Method Details

.render(input, context = "", io: StringIO.new, timeout: DEFAULT_TIMEOUT, ruby: {}) ⇒ Object



13
14
15
16
17
18
19
20
21
# File 'lib/template.rb', line 13

def self.render(
  input,
  context = "",
  io: StringIO.new,
  timeout: DEFAULT_TIMEOUT,
  ruby: {}
)
  new(input, io: io, timeout: timeout, ruby: ruby).render(context)
end

Instance Method Details

#render(context = "") ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/template.rb', line 23

def render(context = "")
  Timeout.timeout(timeout) do
    if context != ""
      context = ::Code.evaluate(context, timeout: timeout, io: io, ruby: ruby)
    else
      context = ::Code::Object::Dictionnary.new
    end

    if !context.is_a?(::Code::Object::Dictionnary)
      raise ::Code::Template::IncompatibleContext.new(
              "context must be a dictionnary"
            )
    end

    context = context.merge(ruby)

    ::Template::Node::Template.new(parsed).evaluate(context: context, io: io)

    io.is_a?(StringIO) ? io.string : nil
  end
end