Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 79 lines (68 sloc) 1.766 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 don...
authored
9 @test_args = options[:test_args]
10 @test_match = options[:test_match]
c00ee39 @josh Support "nodejs" binary name
josh authored
11 @binary = locate_binary
954db08 @sstephenson Instantiate with options instead of subclassing
authored
12 end
13
0be476d @sstephenson Extract ExecJS::Runtime
authored
14 def eval(source)
15 if /\S/ =~ source
16 exec("return eval(#{"(#{source})".to_json})")
17 end
18 end
19
c5e22c4 @sstephenson Runtime -> ExternalRuntime
authored
20 def exec(source)
21 compile_to_tempfile(source) do |file|
22 extract_result(exec_runtime(file.path))
23 end
24 end
25
b22082f @sstephenson Add Runtime#available?
authored
26 def available?
c00ee39 @josh Support "nodejs" binary name
josh authored
27 @binary ? true : false
b22082f @sstephenson Add Runtime#available?
authored
28 end
29
0be476d @sstephenson Extract ExecJS::Runtime
authored
30 protected
c00ee39 @josh Support "nodejs" binary name
josh authored
31 def locate_binary
32 @command = @command.join(" ") if @command.is_a?(Array)
33 if binary = `which #{@command}`.split("\n").first
34 if @test_args
35 output = `#{binary} #{@test_args} 2>&1`
36 binary if output.match(@test_match)
37 else
38 binary
39 end
40 end
41 end
42
0be476d @sstephenson Extract ExecJS::Runtime
authored
43 def compile(source)
44 runner_source.sub('#{source}', source)
45 end
46
47 def runner_source
954db08 @sstephenson Instantiate with options instead of subclassing
authored
48 @runner_source ||= IO.read(@runner_path)
0be476d @sstephenson Extract ExecJS::Runtime
authored
49 end
50
51 def compile_to_tempfile(source)
52 tempfile = Tempfile.open("execjs")
53 tempfile.write compile(source)
54 tempfile.close
55 yield tempfile
56 ensure
57 tempfile.close!
58 end
59
60 def exec_runtime(filename)
c00ee39 @josh Support "nodejs" binary name
josh authored
61 output = `#{@binary} #{filename} 2>&1`
0be476d @sstephenson Extract ExecJS::Runtime
authored
62 if $?.success?
63 output
64 else
65 raise RuntimeError, output
66 end
67 end
68
69 def extract_result(output)
70 status, value = output.empty? ? [] : JSON.parse(output)
71 if status == "ok"
72 value
73 else
74 raise ProgramError, value
75 end
76 end
77 end
78 end
Something went wrong with that request. Please try again.