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

Add Context#call

This commit is contained in:
Joshua Peek 2011-02-12 12:27:08 -06:00
parent 4bc602f41d
commit 50791dd9da
5 changed files with 52 additions and 3 deletions

View file

@ -9,6 +9,12 @@ module ExecJS
@script = ""
end
def <<(script)
@script << script
@script << "\n"
self
end
def eval(source, options = {})
if /\S/ =~ source
exec("return eval(#{"(#{source})".to_json})")
@ -16,9 +22,10 @@ module ExecJS
end
def exec(source, options = {})
if !options[:pure]
@script << source
@script << "\n"
if options[:pure]
source = @script + source
else
self << source
source = @script
end
@ -27,6 +34,10 @@ module ExecJS
end
end
def call(properties, *args)
eval "#{properties}.apply(this, #{args.to_json})"
end
protected
def compile_to_tempfile(source)
tempfile = Tempfile.open("execjs")

View file

@ -23,6 +23,16 @@ module ExecJS
end
end
def call(properties, *args)
unbox @v8_context.eval(properties).call(*args)
rescue ::V8::JSError => e
if e.value["name"] == "SyntaxError"
raise RuntimeError, e
else
raise ProgramError, e
end
end
def unbox(value)
case value
when ::V8::Function

View file

@ -23,6 +23,16 @@ module ExecJS
end
end
def call(properties, *args)
unbox @rhino_context.eval(properties).call(*args)
rescue ::Rhino::JavascriptError => e
if e.message == "syntax error"
raise RuntimeError, e
else
raise ProgramError, e
end
end
def unbox(value)
case value
when ::Rhino::NativeFunction

View file

@ -28,4 +28,21 @@ class TestExecJS < Test::Unit::TestCase
context = ExecJS.compile("foo = function() { return \"bar\"; }")
assert_equal "bar", context.eval("foo()", :pure => true)
end
def test_context_call
context = ExecJS.compile("id = function(v) { return v; }")
assert_equal "bar", context.call("id", "bar")
end
def test_nested_context_call
context = ExecJS.compile("a = {}; a.b = {}; a.b.id = function(v) { return v; }")
assert_equal "bar", context.call("a.b.id", "bar")
end
def test_context_call_missing_function
context = ExecJS.compile("")
assert_raises ExecJS::ProgramError do
context.call("missing")
end
end
end

View file

@ -33,6 +33,7 @@ module TestRuntime
context = @runtime.compile("foo = function() { return \"bar\"; }")
assert_equal "bar", context.exec("return foo()")
assert_equal "bar", context.eval("foo()")
assert_equal "bar", context.call("foo")
end
def test_this_is_global_scope