Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add Context#call

  • Loading branch information...
commit 50791dd9dab7d522a7bab632ff396b26194536d9 1 parent 4bc602f
@josh josh authored
View
17 lib/execjs/external_runtime.rb
@@ -9,6 +9,12 @@ def initialize(runtime)
@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 @@ def eval(source, options = {})
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 @@ def exec(source, options = {})
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
10 lib/execjs/ruby_racer_runtime.rb
@@ -23,6 +23,16 @@ def eval(source, options = {})
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
10 lib/execjs/ruby_rhino_runtime.rb
@@ -23,6 +23,16 @@ def eval(source, options = {})
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
17 test/test_execjs.rb
@@ -28,4 +28,21 @@ def test_pure_evaluation
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
1  test/test_runtimes.rb
@@ -33,6 +33,7 @@ def test_compile
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
Please sign in to comment.
Something went wrong with that request. Please try again.