This repository has been archived by the owner on Jun 10, 2018. It is now read-only.
forked from rails/execjs
/
ruby_racer_runtime.rb
87 lines (76 loc) · 1.84 KB
/
ruby_racer_runtime.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
module ExecJS
class RubyRacerRuntime
class Context
def initialize(source = "")
@v8_context = ::V8::Context.new
@v8_context.eval(source)
end
def exec(source, options = {})
souce = source.encode('UTF-8') if source.respond_to?(:encode)
if /\S/ =~ source
eval "(function(){#{source}})()", options
end
end
def eval(source, options = {})
souce = source.encode('UTF-8') if source.respond_to?(:encode)
if /\S/ =~ source
unbox @v8_context.eval("(#{source})")
end
rescue ::V8::JSError => e
if e.value["name"] == "SyntaxError"
raise RuntimeError, e
else
raise ProgramError, e
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
nil
when ::V8::Array
value.map { |v| unbox(v) }
when ::V8::Object
value.inject({}) do |vs, (k, v)|
vs[k] = unbox(v) unless v.is_a?(::V8::Function)
vs
end
when String
value.respond_to?(:force_encoding) ?
value.force_encoding('UTF-8') :
value
else
value
end
end
end
def name
"therubyracer (V8)"
end
def exec(source)
context = Context.new
context.exec(source)
end
def eval(source)
context = Context.new
context.eval(source)
end
def compile(source)
Context.new(source)
end
def available?
require "v8"
true
rescue LoadError
false
end
end
end