These are my personal implementations of Dir.home and Dir.temp.
I added some examples as well.
gegroet,
Erik V. - http://www.erikveen.dds.nl/
class Dir
def self.home(*args, &block)
dir = nil
dir ||= ENV["HOME"]
dir ||= ENV["USERPROFILE"]
dir ||= "c:/"
handle_home_and_temp(dir, *args, &block)
end
def self.temp(*args, &block)
dir = nil
dir ||= ENV["TMPDIR"]
dir ||= ENV["TMP"]
dir ||= ENV["TEMP"]
dir ||= "/tmp"
handle_home_and_temp(dir, *args, &block)
end
private
def self.handle_home_and_temp(dir, *args, &block)
file = File.join(*args)
file = file.gsub(/\/, “/”)
file = file.gsub(//+/, “/”)
file = file.gsub(/^/+/, “”)
file = file.gsub(//+$/, “”)
dir = dir.gsub(/\\/, "/")
dir = dir.gsub(/\/+/, "/")
dir = dir.gsub(/\/+$/, "")
dir = File.expand_path(file, dir)
res = dir
if block
pdir = Dir.pwd
Dir.chdir(dir) # Ruby 1.6 doesn't handle Dir.chdir(&block).
res = block.call(res)
Dir.chdir(pdir)
end
res
end
end
p Dir.home
p Dir.home{Dir.pwd}
p Dir.home(“a”, “b”)
p Dir.home(“a”, “b”){Dir.pwd}
p Dir.temp
p Dir.temp{Dir.pwd}
p Dir.temp(“c”, “d”)
p Dir.temp(“c”, “d”){Dir.pwd}