1
0
Fork 0
mirror of https://github.com/rails/execjs synced 2023-03-27 23:21:20 -04:00

Extract ExecJS::Runtime

This commit is contained in:
Sam Stephenson 2011-02-06 19:28:28 -06:00
parent 6a1bf0c9c8
commit 0be476df21
4 changed files with 62 additions and 52 deletions

View file

@ -3,6 +3,7 @@ module ExecJS
class RuntimeError < Error; end class RuntimeError < Error; end
class ProgramError < Error; end class ProgramError < Error; end
autoload :Runtime, "execjs/runtime"
autoload :Runtimes, "execjs/runtimes" autoload :Runtimes, "execjs/runtimes"
def self.exec(source) def self.exec(source)
@ -14,6 +15,6 @@ module ExecJS
end end
def self.runtime def self.runtime
@runtime ||= Runtimes::Node @runtime ||= Runtimes::Node.new
end end
end end

54
lib/execjs/runtime.rb Normal file
View file

@ -0,0 +1,54 @@
require "json"
require "tempfile"
module ExecJS
class Runtime
def exec(source)
compile_to_tempfile(source) do |file|
extract_result(exec_runtime(file.path))
end
end
def eval(source)
if /\S/ =~ source
exec("return eval(#{"(#{source})".to_json})")
end
end
protected
def compile(source)
runner_source.sub('#{source}', source)
end
def runner_source
@runner_source ||= IO.read(runner_path)
end
def compile_to_tempfile(source)
tempfile = Tempfile.open("execjs")
tempfile.write compile(source)
tempfile.close
yield tempfile
ensure
tempfile.close!
end
def exec_runtime(filename)
output = `#{command(filename)} 2>&1`
if $?.success?
output
else
raise RuntimeError, output
end
end
def extract_result(output)
status, value = output.empty? ? [] : JSON.parse(output)
if status == "ok"
value
else
raise ProgramError, value
end
end
end
end

View file

@ -1,58 +1,13 @@
require "json"
require "tempfile"
module ExecJS module ExecJS
module Runtimes module Runtimes
module Node class Node < Runtime
extend self def command(filename)
"node #{filename}"
def exec(source)
compile_to_tempfile(source) do |file|
extract_result(exec_runtime("node #{file.path}"))
end
end end
def eval(source) def runner_path
if /\S/ =~ source File.expand_path('../node.js', __FILE__)
exec("return eval(#{"(#{source})".to_json})")
end
end end
protected
def compile_to_tempfile(source)
tempfile = Tempfile.open("execjs")
tempfile.write compile(source)
tempfile.close
yield tempfile
ensure
tempfile.close!
end
def compile(source)
wrapper.sub('#{source}', source)
end
def wrapper
@wrapper ||= IO.read(File.expand_path('../node.js', __FILE__))
end
def exec_runtime(command)
output = `#{command} 2>&1`
if $?.success?
output
else
raise RuntimeError, output
end
end
def extract_result(output)
status, value = output.empty? ? [] : JSON.parse(output)
if status == "ok"
value
else
raise ProgramError, value
end
end
end end
end end
end end

View file

@ -3,7 +3,7 @@ require "test/unit"
class TestNodeRuntime < Test::Unit::TestCase class TestNodeRuntime < Test::Unit::TestCase
def setup def setup
@runtime = ExecJS::Runtimes::Node @runtime = ExecJS::Runtimes::Node.new
end end
def test_exec def test_exec