Created
November 11, 2014 15:48
-
-
Save seamusabshere/cc4f4abb26faf5957c2f to your computer and use it in GitHub Desktop.
safe tmp paths including keeping extname
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
# requires the zaru gem, just get it :) | |
require 'tmpdir' | |
require 'zaru' | |
def tmp_path(name_hint = nil) | |
name_hint ||= 'tmp' | |
extname = File.extname name_hint | |
name_hint = Zaru.sanitize! File.basename(name_hint, extname).to_s.gsub(/\s+/, '_') | |
path = Dir::Tmpname.create(name_hint) {} | |
"#{path}#{extname}" | |
end | |
puts tmp_path('foo') | |
puts tmp_path('foo.csv') | |
# $ ruby foo.rb | |
# /var/folders/y5/qt_wf5l52jd12gzd8dxfqpt40000gp/T/foo20141111-57832-vmjgjk | |
# /var/folders/y5/qt_wf5l52jd12gzd8dxfqpt40000gp/T/foo20141111-57832-1f7t8xa.csv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm going to leave this for a future optimization because the Dir::Tmpname doesn't offer the free tempfile cleanup feature