Module: Philiprehberger::SafeExec

Defined in:
lib/philiprehberger/safe_exec.rb,
lib/philiprehberger/safe_exec/parser.rb,
lib/philiprehberger/safe_exec/version.rb,
lib/philiprehberger/safe_exec/compiled.rb,
lib/philiprehberger/safe_exec/evaluator.rb,
lib/philiprehberger/safe_exec/tokenizer.rb

Defined Under Namespace

Modules: Tokenizer Classes: Compiled, Error, Evaluator, Parser, TimeoutError

Constant Summary collapse

DEFAULT_TIMEOUT =
5
BUILTIN_FUNCTIONS =
%w[min max abs length round sqrt ceil floor pow upcase downcase trim].freeze
VERSION =
'0.4.0'

Class Method Summary collapse

Class Method Details

.compile(expr) ⇒ Compiled

Pre-parse an expression so it can be evaluated repeatedly against different contexts without re-tokenizing or re-parsing.

Parameters:

  • expr (String)

    the expression to compile

Returns:

  • (Compiled)

    a reusable compiled expression

Raises:

  • (Error)

    if the expression fails to tokenize or parse



37
38
39
# File 'lib/philiprehberger/safe_exec.rb', line 37

def self.compile(expr)
  Compiled.new(expr)
end

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

Evaluate a sandboxed expression with an optional context

Parameters:

  • expr (String)

    the expression to evaluate

  • 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 parse or evaluation errors

  • (TimeoutError)

    if evaluation exceeds the timeout



27
28
29
# File 'lib/philiprehberger/safe_exec.rb', line 27

def self.evaluate(expr, context = {}, timeout: DEFAULT_TIMEOUT)
  compile(expr).evaluate(context, timeout: timeout)
end