class NodeRunner

Constants

VERSION

Public Class Methods

new(source = "", options = {}) click to toggle source
# File lib/node-runner.rb, line 8
def initialize(source = "", options = {})
  @source  = encode(source.strip)
  @args = options[:args] || {}
  @executor = options[:executor] || NodeRunner::Executor.new
  @function_name = options[:function_name] || "main"
end

Public Instance Methods

method_missing(m, *args, &block) click to toggle source
# File lib/node-runner.rb, line 19
def method_missing(m, *args, &block)
  @function_name = m
  if block
    @source = encode(block.call.strip)
  end
  @args = *args
  exec
end
output() click to toggle source
# File lib/node-runner.rb, line 15
def output
  exec
end

Protected Instance Methods

create_tempfile(basename) click to toggle source
# File lib/node-runner.rb, line 46
def create_tempfile(basename)
  tmpfile = nil
  Dir::Tmpname.create(basename) do |tmpname|
    mode    = File::WRONLY | File::CREAT | File::EXCL
    tmpfile = File.open(tmpname, mode, 0600)
  end
  tmpfile
end
encode(string) click to toggle source
# File lib/node-runner.rb, line 30
def encode(string)
  string.encode('UTF-8')
end
exec() click to toggle source
# File lib/node-runner.rb, line 34
def exec
  source = @executor.compile_source(@source, @args.to_json, @function_name)
  tmpfile = write_to_tempfile(source)
  filepath = tmpfile.path

  begin
    extract_result(@executor.exec(filepath), filepath)
  ensure
    File.unlink(tmpfile)
  end
end
extract_result(output, filename) click to toggle source
# File lib/node-runner.rb, line 62
def extract_result(output, filename)
  status, value, stack = output.empty? ? [] : ::JSON.parse(output, create_additions: false)
  if status == "ok"
    value
  else
    stack ||= ""
    real_filename = File.realpath(filename)
    stack = stack.split("\n").map do |line|
      line.sub(" at ", "")
          .sub(real_filename, "node_runner")
          .sub(filename, "node_runner")
          .strip
    end
    stack.shift # first line is already part of the message (aka value)
    error = NodeRunnerError.new(value)
    error.set_backtrace(stack + caller)
    raise error
  end
end
write_to_tempfile(contents) click to toggle source
# File lib/node-runner.rb, line 55
def write_to_tempfile(contents)
  tmpfile = create_tempfile(['node_runner', 'js'])
  tmpfile.write(contents)
  tmpfile.close
  tmpfile
end