-
Notifications
You must be signed in to change notification settings - Fork 282
/
ruby_rhino_runtime.rb
102 lines (86 loc) · 2.68 KB
/
ruby_rhino_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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
require "execjs/runtime"
require "json"
module ExecJS
class RubyRhinoRuntime < Runtime
class Context < Runtime::Context
def initialize(runtime, source = "", options = {})
source = source.encode(Encoding::UTF_8)
@rhino_context = ::Rhino::Context.new
fix_memory_limit! @rhino_context
@rhino_context.eval(source)
rescue Exception => e
raise wrap_error(e)
end
def exec(source, options = {})
source = source.encode(Encoding::UTF_8)
if /\S/ =~ source
eval "(function(){#{source}})()", options
end
end
def eval(source, options = {})
source = source.encode(Encoding::UTF_8)
if /\S/ =~ source
unbox @rhino_context.eval("(#{source})")
end
rescue Exception => e
raise wrap_error(e)
end
def call(properties, *args)
# Might no longer be necessary if therubyrhino handles Symbols directly:
# https://github.com/rubyjs/therubyrhino/issues/43
converted_args = JSON.parse(JSON.generate(args), create_additions: false)
unbox @rhino_context.eval(properties).call(*converted_args)
rescue Exception => e
raise wrap_error(e)
end
def unbox(value)
case value = ::Rhino::to_ruby(value)
when Java::OrgMozillaJavascript::NativeFunction
nil
when Java::OrgMozillaJavascript::NativeObject
value.inject({}) do |vs, (k, v)|
case v
when Java::OrgMozillaJavascript::NativeFunction, ::Rhino::JS::Function
nil
else
vs[k] = unbox(v)
end
vs
end
when Array
value.map { |v| unbox(v) }
else
value
end
end
def wrap_error(e)
return e unless e.is_a?(::Rhino::JSError)
error_class = e.message == "syntax error" ? RuntimeError : ProgramError
stack = e.backtrace
stack = stack.map { |line| line.sub(" at ", "").sub("<eval>", "(execjs)").strip }
stack.unshift("(execjs):1") if e.javascript_backtrace.empty?
error = error_class.new(e.value.to_s)
error.set_backtrace(stack)
error
end
private
# Disables bytecode compiling which limits you to 64K scripts
def fix_memory_limit!(context)
if context.respond_to?(:optimization_level=)
context.optimization_level = -1
else
context.instance_eval { @native.setOptimizationLevel(-1) }
end
end
end
def name
"therubyrhino (Rhino)"
end
def available?
require "rhino"
true
rescue LoadError
false
end
end
end