Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 75 lines (65 sloc) 1.616 kB
0be476d @sstephenson Extract ExecJS::Runtime
authored
1 require "json"
2 require "tempfile"
3
4 module ExecJS
c5e22c4 @sstephenson Runtime -> ExternalRuntime
authored
5 class ExternalRuntime
954db08 @sstephenson Instantiate with options instead of subclassing
authored
6 def initialize(options)
7 @command = options[:command]
8 @runner_path = options[:runner_path]
5d0d51b @sstephenson therubyracer gem installs an incompatible `v8` binary - make sure we …
authored
9 @test_args = options[:test_args]
10 @test_match = options[:test_match]
954db08 @sstephenson Instantiate with options instead of subclassing
authored
11 end
12
0be476d @sstephenson Extract ExecJS::Runtime
authored
13 def eval(source)
14 if /\S/ =~ source
15 exec("return eval(#{"(#{source})".to_json})")
16 end
17 end
18
c5e22c4 @sstephenson Runtime -> ExternalRuntime
authored
19 def exec(source)
20 compile_to_tempfile(source) do |file|
21 extract_result(exec_runtime(file.path))
22 end
23 end
24
b22082f @sstephenson Add Runtime#available?
authored
25 def available?
26 command = @command.split(/\s+/).first
5d0d51b @sstephenson therubyracer gem installs an incompatible `v8` binary - make sure we …
authored
27 binary = `which #{command}`
28 if $? == 0
29 if @test_args
30 output = "#{binary} #{@test_args} 2>&1"
31 output.match(@test_match)
32 else
33 true
34 end
35 end
b22082f @sstephenson Add Runtime#available?
authored
36 end
37
0be476d @sstephenson Extract ExecJS::Runtime
authored
38 protected
39 def compile(source)
40 runner_source.sub('#{source}', source)
41 end
42
43 def runner_source
954db08 @sstephenson Instantiate with options instead of subclassing
authored
44 @runner_source ||= IO.read(@runner_path)
0be476d @sstephenson Extract ExecJS::Runtime
authored
45 end
46
47 def compile_to_tempfile(source)
48 tempfile = Tempfile.open("execjs")
49 tempfile.write compile(source)
50 tempfile.close
51 yield tempfile
52 ensure
53 tempfile.close!
54 end
55
56 def exec_runtime(filename)
954db08 @sstephenson Instantiate with options instead of subclassing
authored
57 output = `#{@command} #{filename} 2>&1`
0be476d @sstephenson Extract ExecJS::Runtime
authored
58 if $?.success?
59 output
60 else
61 raise RuntimeError, output
62 end
63 end
64
65 def extract_result(output)
66 status, value = output.empty? ? [] : JSON.parse(output)
67 if status == "ok"
68 value
69 else
70 raise ProgramError, value
71 end
72 end
73 end
74 end
Something went wrong with that request. Please try again.