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.5")

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.



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/template.rb', line 8

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

Class Method Details

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



20
21
22
23
24
25
26
27
28
# File 'lib/template.rb', line 20

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



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/template.rb', line 30

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

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

    context = context.merge(ruby)

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

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