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

@ -1,9 +1,10 @@
require "rbconfig"
module ExecJS
class Error < ::StandardError; end
class RuntimeError < Error; end
class ProgramError < Error; end
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)
runtime.exec(source)
class << self
attr_reader :runtime
def exec(source)
runtime.exec(source)
end
def eval(source)
runtime.eval(source)
end
def compile(source)
runtime.compile(source)
end
def runtimes
Runtimes.runtimes
end
def runtime=(runtime)
raise RuntimeUnavailable, "#{runtime.name} is unavailable on this system" unless runtime.available?
@runtime = runtime
end
def root
@root ||= File.expand_path("../execjs", __FILE__)
end
def windows?
@windows ||= RbConfig::CONFIG["host_os"] =~ /mswin|mingw/
end
end
def self.eval(source)
runtime.eval(source)
end
def self.compile(source)
runtime.compile(source)
end
def self.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.")
end
def self.root
@root ||= File.expand_path("../execjs", __FILE__)
end
def self.windows?
@windows ||= RbConfig::CONFIG["host_os"] =~ /mswin|mingw/
end
# Eager detect runtime
self.runtime
# 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()")