2007年 10月 15日

そういえば tmpdir が予想と違った

なんとなく Tempfile の親戚だとおもって /tmp/hoge.9999.1 とかかえすとおもったら、たんに /tmp とか返すだけだった。

で、そういうディレクトリが欲しいときって自分で $$ とか書かないといけなくて嫌なんだけど、Tempfile はファイルを作って返すので使えず残念な感じになってしまう。個人的には Pathname に一時的なパスをつくるメソッドがあればいいと思った。

require "tmpdir"
require "pathname"

class Pathname
	@@tempname_number = 0
	def self.tempname(base=$0, dir=Dir.tmpdir)
		@@tempname_number += 1
		name = "#{dir}/#{File.basename(base)}.#{$$}.#{@@tempname_number}"
		path = new(name)
		at_exit do
			path.rmtree if path.exist?
		end
		path
	end
end

# ファイル
Pathname.tempname.open("w") do |f|
	f << "aaaaa"
end

# ディレクトリ
path =  Pathname.tempname
path.mkpath
10.times do |i|
	(path+"test#{i}.rb").open("w") {|f| f << "test" }
end

こんな感じのやつがほしい。特別ファイルをつくったりせず (Pathname なら作るの簡単だし)、ファイルでもディレクトリでもつかえる。

at_exit とファイナライザだと at_exit のほうが簡単な気がするけど、なんか問題あるのかな。デーモンだとたくさんできすぎるからかな。

そういえば、Pathname#mkpath が nil を返すけど、self を返してほしいと思うなぁ。

dir = Pathname.tempname.mkpath

みたいに書けると幸せ