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

EMPTY_STRING =
""
GLOBALS =
%i[io context object].freeze
DEFAULT_TIMEOUT =
0
Version =
Gem::Version.new("0.6.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.



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

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 = Timeout.timeout(timeout) { ::Code::Ruby.to_code(ruby || {}).code_to_context }
end

Class Method Details

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



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

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

Instance Method Details

#evaluate(context = "") ⇒ Object



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

def evaluate(context = "")
  Timeout.timeout(timeout) do
    context =
      if context == EMPTY_STRING
        Object::Context.new
      else
        Code.evaluate(context, timeout:, io:, ruby:).code_to_context
      end

    raise(Error::IncompatibleContext) unless context.is_a?(::Code::Object::Context)

    context = context.merge(ruby)

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

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