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

Active runtime can be overridden with ExecJS.runtime=

This commit is contained in:
Sam Stephenson 2011-05-17 10:08:41 -05:00
parent 8d3e05f331
commit 71354867bc
2 changed files with 49 additions and 32 deletions

View file

@ -4,6 +4,7 @@ module ExecJS
class Error < ::StandardError; end
class RuntimeError < Error; end
class ProgramError < Error; end
class RuntimeUnavailable < RuntimeError; end
autoload :ExternalRuntime, "execjs/external_runtime"
autoload :MustangRuntime, "execjs/mustang_runtime"
@ -11,35 +12,40 @@ module ExecJS
autoload :RubyRhinoRuntime, "execjs/ruby_rhino_runtime"
autoload :Runtimes, "execjs/runtimes"
def self.exec(source)
class << self
attr_reader :runtime
def exec(source)
runtime.exec(source)
end
def self.eval(source)
def eval(source)
runtime.eval(source)
end
def self.compile(source)
def compile(source)
runtime.compile(source)
end
def self.runtimes
def runtimes
Runtimes.runtimes
end
def self.runtime
@runtime ||= Runtimes.best_available ||
raise(ExecJS::RuntimeError, "Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes.")
def runtime=(runtime)
raise RuntimeUnavailable, "#{runtime.name} is unavailable on this system" unless runtime.available?
@runtime = runtime
end
def self.root
def root
@root ||= File.expand_path("../execjs", __FILE__)
end
def self.windows?
def windows?
@windows ||= RbConfig::CONFIG["host_os"] =~ /mswin|mingw/
end
# Eager detect runtime
self.runtime
end
# Eagerly detect runtime
self.runtime ||= Runtimes.best_available ||
raise(RuntimeUnavailable, "Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes.")
end

View file

@ -18,6 +18,17 @@ class TestExecJS < Test::Unit::TestCase
assert runtime.available?
end
def test_runtime_assignment
original_runtime = ExecJS.runtime
runtime = ExecJS::ExternalRuntime.new(:command => "nonexistent")
assert_raises(ExecJS::RuntimeUnavailable) { ExecJS.runtime = runtime }
assert_equal original_runtime, ExecJS.runtime
runtime = ExecJS::ExternalRuntime.new(:command => "ruby")
ExecJS.runtime = runtime
assert_equal runtime, ExecJS.runtime
end
def test_compile
context = ExecJS.compile("foo = function() { return \"bar\"; }")
assert_equal "bar", context.exec("return foo()")