Skip to content
This repository has been archived by the owner on Jun 10, 2018. It is now read-only.

Commit

Permalink
Add therubyracer V8 runtime implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
sstephenson committed Feb 7, 2011
1 parent 5d0d51b commit 957d632
Show file tree
Hide file tree
Showing 6 changed files with 59 additions and 6 deletions.
1 change: 1 addition & 0 deletions lib/execjs.rb
Expand Up @@ -5,6 +5,7 @@ class ProgramError < Error; end

autoload :ExternalRuntime, "execjs/external_runtime"
autoload :Runtimes, "execjs/runtimes"
autoload :V8Runtime, "execjs/v8_runtime"

def self.exec(source)
runtime.exec(source)
Expand Down
4 changes: 2 additions & 2 deletions lib/execjs/external_runtime.rb
Expand Up @@ -24,10 +24,10 @@ def exec(source)

def available?
command = @command.split(/\s+/).first
binary = `which #{command}`
binary = `which #{command}`.strip
if $? == 0
if @test_args
output = "#{binary} #{@test_args} 2>&1"
output = `#{binary} #{@test_args} 2>&1`
output.match(@test_match)
else
true
Expand Down
3 changes: 3 additions & 0 deletions lib/execjs/runtimes.rb
Expand Up @@ -19,6 +19,9 @@ def self.runner_path(path)
end

define_runtime :V8,
:as => V8Runtime

define_runtime :ExternalV8,
:command => "v8",
:test_args => "--help",
:test_match => /--crankshaft/,
Expand Down
48 changes: 48 additions & 0 deletions lib/execjs/v8_runtime.rb
@@ -0,0 +1,48 @@
module ExecJS
class V8Runtime
def initialize(options)
end

def exec(source)
if /\S/ =~ source
eval "(function(){#{source}})()"
end
end

def eval(source)
if /\S/ =~ source
context = ::V8::Context.new
unbox context.eval("(#{source})")
end
rescue ::V8::JSError => e
if e.value["name"] == "SyntaxError"
raise RuntimeError, e
else
raise ProgramError, e
end
end

def available?
require "v8"
true
rescue LoadError
false
end

def unbox(value)
case value
when ::V8::Function
nil
when ::V8::Array
value.map { |v| unbox(v) }
when ::V8::Object
value.inject({}) do |vs, (k, v)|
vs[k] = unbox(v) unless v.is_a?(::V8::Function)
vs
end
else
value
end
end
end
end
4 changes: 2 additions & 2 deletions test/test_execjs.rb
Expand Up @@ -12,9 +12,9 @@ def test_eval

def test_runtime_available
runtime = ExecJS::ExternalRuntime.new(:command => "nonexistent")
assert_equal false, runtime.available?
assert !runtime.available?

runtime = ExecJS::ExternalRuntime.new(:command => "ruby")
assert_equal true, runtime.available?
assert runtime.available?
end
end
5 changes: 3 additions & 2 deletions test/test_runtimes.rb
Expand Up @@ -58,7 +58,8 @@ def test_runtime(name)
end
end

test_runtime :JSC
test_runtime :V8
test_runtime :ExternalV8
test_runtime :Node
test_runtime :JSC
test_runtime :Spidermonkey
test_runtime :V8

0 comments on commit 957d632

Please sign in to comment.