| Module | TempPath |
| In: |
lib/temp_path.rb
|
By default the autoclean is on. But in some case (if you use your temppaths in at_exit) You must disable the autoclean. And manually call TempPath.clean at the very of the program.
# File lib/temp_path.rb, line 113 def clean ( &block ) @@mutex.synchronize do return if @@clean_planned @@clean_planned = true end begin block[] if block_given? ensure if @@tmpdir.exist? @@tmpdir.rmtree @@initialized = false end end end
Call TempPath.fork_init when you want to reset the global TempPath status. For example when you make a fork and you don‘t want that the child have and destroy the same temporary directory as the father. This method setup a child TempPath environement where the temporary directory of the child is in the father one (unless if you set sub_dir to false)
# File lib/temp_path.rb, line 103 def fork_init ( sub_dir=true ) @@tmpdir ||= nil @@initialized = false init((sub_dir)? @@tmpdir : nil) end
You can use a temporary pathname like that:
- # No argument are mandatory.
tmp = TempPath.new
tmp.open('w') { |f| f << 'foo' }
tmp.clean
- # You can choose the basename and an extension.
TempPath.new('the_base_file_name', 'rb')
- # You can supply a block (recomended).
TempPath.new('foo') do |tmp|
tmp.open('w') { |f| << 'foo' }
tmp.exist? == true
$tmp = tmp
end
$tmp.exist? == false
- # You can make a temporary directory.
TempPath.new('adirectory') do |tmpdir|
tmpdir.mkpath
$file = tmpdir + 'foo'
$file.open('w') { |f| f << 'foo' }
end
$file.exist? == false
The file name follow this scheme:
TempPath.new(‘foo’, ‘rb’)
=> 'foo.111811.432.rb'
TempPath.new(‘bar’)
=> 'bar.111811.134'
which follow this format:
=> 'base.pid.uniq.ext
# File lib/temp_path.rb, line 54 def new base=nil, ext='', &block tmp = nil if base and base.to_s =~ /\// raise ArgumentError, "bad basename, you give me a pathname #{base}" end init base ||= @@progname ext = ".#{ext}" unless ext.empty? or ext[0] == ?. res = nil @@mutex.synchronize do tmp = Pathname.new '' id_tmp = tmp.object_id while (res = @@tmpdir + "#{base}.#{id_tmp}#{ext}").exist? \ and not @@tmps.include? res id_tmp += 1 end tmp.instance_eval { @path = res.instance_eval { @path } } tmp.extend TempPathname @@tmps << self end return tmp unless block_given? begin return block[tmp.dup] ensure tmp.clean end end