How to Create Temp Dir in Ruby

How to create temp dir in Ruby?

See documentation for tmpdir. If mktmpdir method is provided with a block, the temp dir will be removed when block returns. In your case, you would call without a block and handle removal later (=program exit).

Regarding automatic removal on exit, I think tmpdir won't do that for you. However, at_exit should help.

As an example, Homebrew does it like this:

require 'tmpdir'

# rest omitted

TEST_TMPDIR = ENV.fetch("HOMEBREW_TEST_TMPDIR") do |k|
dir = Dir.mktmpdir("homebrew-tests-", ENV["HOMEBREW_TEMP"] || "/tmp")
at_exit { FileUtils.remove_entry(dir) }
ENV[k] = dir
end

ruby Temporary files inside temporary directory

You should use the Tempfile class.

require 'tempfile'

file = Tempfile.new('foo')
file.path # => A unique filename in the OS's temp directory,
# e.g.: "/tmp/foo.24722.0"
# This filename contains 'foo' in its basename.
file.write("hello world")
file.rewind
file.read # => "hello world"
file.close
file.unlink # deletes the temp file

To create temporary folders, you can use Dir.mktmpdir.

What is the best way to get an empty temporary directory in Ruby on Rails?

The Dir#tmpdir function in the Ruby core (not stdlib that you linked to) should be cross-platform.

To use this function you need to require 'tmpdir'.

Change tmp folder for uploaded files

If setting the TMPDIR,TMP,TEMP is not working, it could be that the directory you specified doesn't exist or is not writable. Or $SAFE variable is > 0. The tmp folder is determined using the function Dir.tmpdir (see http://www.ruby-doc.org/stdlib-1.9.3/libdoc/tmpdir/rdoc/Dir.html#method-c-tmpdir).

class Dir  
def Dir::tmpdir
tmp = '.'
if $SAFE > 0
tmp = @@systmpdir
else
for dir in [ENV['TMPDIR'], ENV['TMP'], ENV['TEMP'], @@systmpdir, '/tmp']
if dir and stat = File.stat(dir) and stat.directory? and stat.writable?
tmp = dir
break
end rescue nil
end
File.expand_path(tmp)
end
end
end

Ruby 2.1

def Dir::tmpdir
if $SAFE > 0
tmp = @@systmpdir
else
tmp = nil
for dir in [ENV['TMPDIR'], ENV['TMP'], ENV['TEMP'], @@systmpdir, '/tmp', '.']
next if !dir
dir = File.expand_path(dir)
if stat = File.stat(dir) and stat.directory? and stat.writable? and
(!stat.world_writable? or stat.sticky?)
tmp = dir
break
end rescue nil
end
raise ArgumentError, "could not find a temporary directory" if !tmp
tmp
end
end

So if you're setting the TMP env variables, make sure that the lines below are true

  1. $SAFE == 0
  2. File.stat("you_dir")
  3. File.stat("you_dir").directory?
  4. File.stat("you_dir").writable?

Another way to set tempdir is to override the tmpdir in your rails initializer, but obviously this bypasses any directory checking so u gotta make sure it exists/writable

class Dir
def self.tmpdir
"/your_directory/"
end
end

Ruby: Could not find a temporary directory

Not sure what happened here, but I believe it had something to do with the /tmp folder permissions. I thought my /tmp folder was corrupted so I looked around about deleteing that folder and restoring it (I wasn't sure if this folder was especially significant about the way it was created). I found this source that suggested you can simply make the /tmp folder, just as you would any other folder, and then do a chmod 1777 on the newly created folder.

So, instead of deleting my current /tmp, I ran this chmod command and everything appeared to work.

What is strange to me is that I had previously done a chmod 777 and that caused the folder to not work. Weird...

Change temporary directory in Rails 4

It seems that some libraries like to hard code values... See: [1]

By adding the following you can get around the hard coded value:

  config.assets.cache_limit = 50.megabytes

config.assets.configure do |env|
env.cache = Sprockets::Cache::FileStore.new(
File.join(ENV['RAILS_TMP'], 'cache/assets'),
config.assets.cache_limit,
env.logger
)
end

Specify a non-standard temporary directory for open() method in Ubuntu

Looking at the OpenURI source code we can see that it uses Tempfile:

[...]
io = Tempfile.new('open-uri')
[...]

Tempfile in order to choose the temporary directory uses Dir.tmpdir, which in turn uses the system temporary directory or a directory specified by the environment variable TMPDIR (between others). So we can write something like this:

require 'open-uri'
require 'fileutils'

d = "#{Dir.home}/.tmp"
Dir.mkdir d
ENV["TMPDIR"] = d
p open("http://www.google.com")
ENV.delete("TMPDIR")
FileUtils.rm_rf d

In a single command (please ensure that $HOME/.tmpdoes not exist and is not used):

ruby -ropen-uri -rfileutils -e 'd = "#{Dir.home}/.tmp"; Dir.mkdir d; ENV["TMPDIR"] = d; p open("http://www.google.com"); ENV.delete("TMPDIR"); FileUtils.rm_rf d'

It should print something like

#<Tempfile:$HOME/.tmp/open-uri20131115-16887-nag9pr>

P.S. I'm using Ruby 2.1.0 preview, so maybe you have to look at #{ruby directory}/lib/ruby/2.0.0/open-uri.rb source in order to understand how OpenURI manages the temporary file (but it should be very similar)

How to generate a temporary file for use in a unit test?

The .create and .new methods of Ruby's Tempfile take a second argument which is the directory you want the file to be in, and files created by Tempfile are automatically deleted when the temporary file's File object is garbage-collected or Ruby exits. So you can create a temporary file,

tempfile = Tempfile.new('filename', 'directoryname')

write to it, do your test and let Ruby clean it up for you.

Note that the first argument is not the entire unqualified name of the file, but a part to which Tempfile adds disambiguating characters, so you can safely do it more than once in a test suite.

Also, if you need the file to have a particular suffix, you can do e.g.

tempfile = Tempfile.new(['filename', '.rb'], 'directoryname')

How can I create a temp file and delete it after a certain amount of time

This is not possible unless you want the Ruby script to run for 30 minutes. It might be easier to store the file in a specific folder (such as /tmp) and have a Cron job automatically wipe files older than a certain time.

How to create a temporary directory?

Use mktemp -d. It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.



Related Topics



Leave a reply



Submit