2011-11-10 11:12:41 -05:00
|
|
|
module V8
|
|
|
|
class Context
|
2012-06-07 11:02:26 -04:00
|
|
|
include Conversion
|
|
|
|
|
2012-05-18 13:44:20 -04:00
|
|
|
attr_reader :native
|
2012-05-01 14:53:01 -04:00
|
|
|
def initialize
|
|
|
|
@native = V8::C::Context::New()
|
2011-11-10 11:12:41 -05:00
|
|
|
end
|
|
|
|
|
2012-06-07 10:28:41 -04:00
|
|
|
def enter(&block)
|
|
|
|
if !entered?
|
|
|
|
lock_scope_and_enter(&block)
|
|
|
|
else
|
|
|
|
yield
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def entered?
|
|
|
|
Context.current == self
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.current
|
|
|
|
Thread.current[:v8_context]
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.current=(context)
|
|
|
|
Thread.current[:v8_context] = context
|
|
|
|
end
|
|
|
|
|
|
|
|
def lock_scope_and_enter
|
|
|
|
current = Context.current
|
|
|
|
Context.current = self
|
|
|
|
V8::C::Locker() do
|
|
|
|
V8::C::HandleScope() do
|
|
|
|
begin
|
|
|
|
@native.Enter()
|
|
|
|
yield if block_given?
|
|
|
|
ensure
|
|
|
|
@native.Exit()
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
ensure
|
|
|
|
Context.current = current
|
|
|
|
end
|
|
|
|
|
2012-05-01 14:53:01 -04:00
|
|
|
def eval(source, filename = '<eval>', line = 1)
|
2012-06-07 10:28:41 -04:00
|
|
|
enter do
|
2012-05-08 16:11:50 -04:00
|
|
|
source = V8::C::String::New(source.to_s)
|
|
|
|
filename = V8::C::String::New(filename.to_s)
|
|
|
|
script = V8::C::Script::New(source, filename)
|
2012-06-07 11:02:26 -04:00
|
|
|
to_ruby script.Run()
|
2012-05-08 16:11:50 -04:00
|
|
|
end
|
2011-11-10 11:12:41 -05:00
|
|
|
end
|
2012-05-08 17:04:47 -04:00
|
|
|
|
|
|
|
def []=(key, value)
|
2012-06-07 10:28:41 -04:00
|
|
|
enter do
|
|
|
|
@native.Global().Set(to_v8(key), to_v8(value))
|
2012-05-08 17:04:47 -04:00
|
|
|
end
|
2012-06-07 10:28:41 -04:00
|
|
|
return value
|
2012-05-08 17:04:47 -04:00
|
|
|
end
|
2012-06-07 10:28:41 -04:00
|
|
|
|
2012-05-08 17:04:47 -04:00
|
|
|
def [](key)
|
2012-06-07 10:28:41 -04:00
|
|
|
enter do
|
|
|
|
to_ruby(@native.Global().Get(to_v8(key)))
|
|
|
|
end
|
|
|
|
end
|
2011-11-10 11:12:41 -05:00
|
|
|
end
|
|
|
|
end
|