Skip to content
This repository has been archived by the owner on Jun 10, 2018. It is now read-only.

Commit

Permalink
Use similar code to Tempfile.create instead of Tempfile.open
Browse files Browse the repository at this point in the history
  • Loading branch information
josh committed Jun 5, 2014
1 parent b88d87d commit b3f5dc6
Showing 1 changed file with 26 additions and 9 deletions.
35 changes: 26 additions & 9 deletions lib/execjs/external_runtime.rb
@@ -1,4 +1,4 @@
require "tempfile"
require "tmpdir"
require "execjs/runtime"

module ExecJS
Expand All @@ -23,8 +23,11 @@ def exec(source, options = {})
source = encode(source)
source = "#{@source}\n#{source}" if @source

compile_to_tempfile(source) do |file|
extract_result(@runtime.send(:exec_runtime, file.path))
tmpfile = compile_to_tempfile(source)
begin
extract_result(@runtime.send(:exec_runtime, tmpfile.path))
ensure
File.unlink(tmpfile)
end
end

Expand All @@ -33,13 +36,27 @@ def call(identifier, *args)
end

protected
# See Tempfile.create on Ruby 2.1
def create_tempfile(basename)
tmpfile = nil
Dir::Tmpname.create(basename) do |tmpname|
mode = File::WRONLY | File::CREAT | File::EXCL
tmpfile = File.open(tmpname, mode, 0600)
end
tmpfile
end

def compile_to_tempfile(source)
tempfile = Tempfile.open(['execjs', '.js'])
tempfile.write compile(source)
tempfile.close
yield tempfile
ensure
tempfile.close!
tmpfile = create_tempfile(['execjs', 'js'])
begin
tmpfile.write compile(source)
tmpfile.close
tmpfile
rescue => e
tmpfile.close unless tmpfile.closed?
File.unlink(tmpfile)
raise e
end
end

def compile(source)
Expand Down

0 comments on commit b3f5dc6

Please sign in to comment.