class ExecJS::ExternalRuntime::Context

Public Class Methods

new(runtime, source = "") click to toggle source
# File lib/execjs/external_runtime.rb, line 7
def initialize(runtime, source = "")
  source = encode(source)

  @runtime = runtime
  @source  = source
end

Public Instance Methods

call(identifier, *args) click to toggle source
# File lib/execjs/external_runtime.rb, line 35
def call(identifier, *args)
  eval "#{identifier}.apply(this, #{::JSON.generate(args)})"
end
eval(source, options = {}) click to toggle source
# File lib/execjs/external_runtime.rb, line 14
def eval(source, options = {})
  source = encode(source)

  if /\S/ =~ source
    exec("return eval(#{::JSON.generate("(#{source})", quirks_mode: true)})")
  end
end
exec(source, options = {}) click to toggle source
# File lib/execjs/external_runtime.rb, line 22
def exec(source, options = {})
  source = encode(source)
  source = "#{@source}\n#{source}" if @source
  source = @runtime.compile_source(source)

  tmpfile = write_to_tempfile(source)
  begin
    extract_result(@runtime.exec_runtime(tmpfile.path))
  ensure
    File.unlink(tmpfile)
  end
end

Protected Instance Methods

create_tempfile(basename) click to toggle source

See Tempfile.create on Ruby 2.1

# File lib/execjs/external_runtime.rb, line 41
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
extract_result(output) click to toggle source
# File lib/execjs/external_runtime.rb, line 57
def extract_result(output)
  status, value = output.empty? ? [] : ::JSON.parse(output, create_additions: false)
  if status == "ok"
    value
  elsif value =~ /SyntaxError:/
    raise RuntimeError, value
  else
    raise ProgramError, value
  end
end
write_to_tempfile(contents) click to toggle source
# File lib/execjs/external_runtime.rb, line 50
def write_to_tempfile(contents)
  tmpfile = create_tempfile(['execjs', 'js'])
  tmpfile.write(contents)
  tmpfile.close
  tmpfile
end