Skip to content

Instantly share code, notes, and snippets.

@seamusabshere
Created November 11, 2014 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seamusabshere/cc4f4abb26faf5957c2f to your computer and use it in GitHub Desktop.
Save seamusabshere/cc4f4abb26faf5957c2f to your computer and use it in GitHub Desktop.
safe tmp paths including keeping extname
# 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
@erithmetic
Copy link

I'm going to leave this for a future optimization because the Dir::Tmpname doesn't offer the free tempfile cleanup feature

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment