Created
November 20, 2016 08:28
-
-
Save umireon/6872f4e1fd2fddd42ba05895502b4e56 to your computer and use it in GitHub Desktop.
Tempfile::create polyfill for Ruby < 2.1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'tempfile' | |
unless Tempfile.respond_to? :create | |
# from https://github.com/ruby/ruby/blob/v2_3_2/lib/tempfile.rb#L326-L343 | |
def Tempfile.create(basename, tmpdir=nil, mode: 0, **options) | |
tmpfile = nil | |
Dir::Tmpname.create(basename, tmpdir, options) do |tmpname, n, opts| | |
mode |= File::RDWR|File::CREAT|File::EXCL | |
opts[:perm] = 0600 | |
tmpfile = File.open(tmpname, mode, opts) | |
end | |
if block_given? | |
begin | |
yield tmpfile | |
ensure | |
tmpfile.close if !tmpfile.closed? | |
File.unlink tmpfile | |
end | |
else | |
tmpfile | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'tempfile' | |
require 'tempfile_create' | |
p Tempfile.new("tmp").class #=> Tempfile | |
p Tempfile.open("tmp").class #=> Tempfile | |
p Tempfile.create("tmp").class #=> File | |
Tempfile.create("tmp") do |fp| | |
p fp.class #=> File | |
end | |
p Tempfile.create("tmp") { 1 } #=> 1 | |
tmpfile = nil | |
Tempfile.create("tmp") do |fp| | |
p fp.closed? #=> false | |
p File.exist?(fp.path) #=> true | |
tmpfile = fp | |
end | |
p tmpfile.closed? #=> true | |
p File.exist? tmpfile.path #=> false | |
Tempfile.create("tmp") do |fp| | |
fp.close | |
end # without any errors | |
begin | |
Tempfile.create("tmp") do |fp| | |
File.unlink fp | |
end | |
rescue Errno::ENOENT => e | |
# No such file or directory @ unlink_internal | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment