From b3f5dc69226c83ab5b3c47ba61c852831eeb2380 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Thu, 5 Jun 2014 14:59:16 -0500 Subject: [PATCH] Use similar code to Tempfile.create instead of Tempfile.open --- lib/execjs/external_runtime.rb | 35 +++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/lib/execjs/external_runtime.rb b/lib/execjs/external_runtime.rb index 01c3fa8..37f9890 100644 --- a/lib/execjs/external_runtime.rb +++ b/lib/execjs/external_runtime.rb @@ -1,4 +1,4 @@ -require "tempfile" +require "tmpdir" require "execjs/runtime" module ExecJS @@ -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 @@ -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)