2010-01-13 17:37:51 +02:00
|
|
|
require 'stringio'
|
|
|
|
|
|
|
|
module V8
|
2009-12-16 07:40:19 +01:00
|
|
|
class Context
|
2010-01-12 23:51:49 +02:00
|
|
|
def initialize(opts = {})
|
|
|
|
@native = C::Context.new(opts[:with])
|
2009-12-16 07:40:19 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def open(&block)
|
2010-01-14 00:51:46 +02:00
|
|
|
if block_given?
|
|
|
|
unless @native == C::Context::GetCurrent()
|
|
|
|
@native.open do
|
|
|
|
block.call(self)
|
|
|
|
end
|
|
|
|
else
|
|
|
|
block.call(self)
|
|
|
|
end
|
|
|
|
end
|
2009-12-16 07:40:19 +01:00
|
|
|
end
|
|
|
|
|
2010-01-10 21:09:11 +02:00
|
|
|
def eval(javascript, sourcename = '<eval>', line = 1)
|
|
|
|
if IO === javascript || StringIO === javascript
|
|
|
|
javascript = javascript.read()
|
|
|
|
end
|
2010-01-17 15:57:05 +02:00
|
|
|
@native.open do
|
|
|
|
@native.eval(javascript).tap do |result|
|
|
|
|
raise JavascriptError.new(result) if result.kind_of?(C::Message)
|
|
|
|
return To.ruby(result)
|
|
|
|
end
|
2010-01-09 18:55:37 +02:00
|
|
|
end
|
2009-12-16 07:40:19 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def evaluate(*args)
|
|
|
|
self.eval(*args)
|
|
|
|
end
|
|
|
|
|
2010-01-10 21:09:11 +02:00
|
|
|
def load(filename)
|
|
|
|
File.open(filename) do |file|
|
|
|
|
evaluate file, filename, 1
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def [](key)
|
2010-01-14 00:51:46 +02:00
|
|
|
open do
|
|
|
|
To.ruby(@native.Global().Get(key.to_s))
|
|
|
|
end
|
2010-01-10 21:09:11 +02:00
|
|
|
end
|
|
|
|
|
2009-12-18 09:48:06 +02:00
|
|
|
def []=(key, value)
|
|
|
|
value.tap do
|
2010-01-14 00:51:46 +02:00
|
|
|
open do
|
|
|
|
@native.Global().tap do |scope|
|
|
|
|
scope.Set(key.to_s, value)
|
|
|
|
end
|
2009-12-18 09:48:06 +02:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2010-01-12 23:51:49 +02:00
|
|
|
def self.open(opts = {}, &block)
|
|
|
|
new(opts).open(&block)
|
2010-01-13 17:37:51 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.eval(source)
|
|
|
|
new.eval(source)
|
|
|
|
end
|
|
|
|
|
|
|
|
def V8.eval(*args)
|
|
|
|
V8::Context.eval(*args)
|
|
|
|
end
|
2009-12-18 09:48:06 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
class ContextError < StandardError
|
2010-01-13 17:13:13 +02:00
|
|
|
def initialize(caller_name)
|
|
|
|
super("tried to call method '#{caller_name} without an open context")
|
|
|
|
end
|
|
|
|
def self.check_open(caller_name)
|
|
|
|
raise new(caller_name) unless C::Context::InContext()
|
|
|
|
end
|
2009-12-18 09:48:06 +02:00
|
|
|
end
|
|
|
|
class JavascriptError < StandardError
|
2010-01-09 18:55:37 +02:00
|
|
|
def initialize(v8_message)
|
|
|
|
super(v8_message.Get())
|
|
|
|
end
|
2009-12-15 07:35:55 +02:00
|
|
|
end
|
2010-01-10 20:56:50 +02:00
|
|
|
class RunawayScriptError < ContextError
|
|
|
|
end
|
2009-12-15 07:35:55 +02:00
|
|
|
end
|