Class: Philiprehberger::SafeExec::Compiled

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/safe_exec/compiled.rb

Overview

A pre-parsed expression that can be evaluated repeatedly against different contexts without re-tokenizing or re-parsing.

Returned by compile. Use this when the same expression is evaluated against many contexts (e.g., rules engines, calculation pipelines).

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ Compiled

Returns a new instance of Compiled.

Parameters:

  • source (String)

    the expression source

Raises:

  • (Error)

    if the source fails to tokenize or parse



17
18
19
20
# File 'lib/philiprehberger/safe_exec/compiled.rb', line 17

def initialize(source)
  @source = source
  @ast = Parser.new(Tokenizer.tokenize(source)).parse
end

Instance Attribute Details

#sourceString (readonly)

Returns the original expression source.

Returns:

  • (String)

    the original expression source



13
14
15
# File 'lib/philiprehberger/safe_exec/compiled.rb', line 13

def source
  @source
end

Instance Method Details

#evaluate(context = {}, timeout: DEFAULT_TIMEOUT) ⇒ Object

Evaluate against a context with optional timeout.

Parameters:

  • context (Hash) (defaults to: {})

    variable bindings

  • timeout (Numeric) (defaults to: DEFAULT_TIMEOUT)

    maximum evaluation time in seconds

Returns:

  • (Object)

    the evaluation result

Raises:

  • (Error)

    on evaluation errors

  • (TimeoutError)

    if evaluation exceeds the timeout



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/philiprehberger/safe_exec/compiled.rb', line 29

def evaluate(context = {}, timeout: DEFAULT_TIMEOUT)
  result = nil
  error = nil

  thread = Thread.new do
    result = Evaluator.new(context).evaluate(@ast)
  rescue Error => e
    error = e
  end

  unless thread.join(timeout)
    thread.kill
    raise TimeoutError, "expression evaluation timed out after #{timeout} seconds"
  end

  raise error if error

  result
end