瞎扯淡 犯 2,重新发明轮子,而且是个瘪轮子

suffering · January 11, 2012 · Last by JohnsonWang replied at February 04, 2012 · 2758 hits

作为一个连 core 与 standard-lib 文档都没看完就要自己写程序的菜鸟,为了写一个能自动生成目录的程序,折腾了良久。结果,昨天去逛 std-lib,才发现原来早就有这样的方法支持了,真是伤啊。 原来的要求是分析 url,而后按 url 的结构来创建目录,最终保存文件到相应的目录。 如http://xxx.xxx.xxx/a/b/c/d.mp3,就要得到 pah,即/a/b/c/d.mp3,而后创建目录a,再在a下创建b,再在 c 下创建b...,创建多少文件夹,分多少级都由 uri 来决定。但是,很明显,若是a,b,中任少一个都不能创建c,因此,也无法使用FIle.open(url.path,"w")这样的方法来直接创建文件了. 在 search 内置方法无果后。我自己写了个程序:

def dir_magic(string, slash = '/')
    return if File.directory?(string)
    _t=string.split(slash)
    _s = _t.shift
    Dir.mkdir(_s) if !File.directory?(_s)
    return if _t.empty?
    if File.directory?(_s)
        Dir.chdir(_s) do
            dir_magic(_t.join(slash))
        end
    end
end

这个方法让我很蛋疼。 首先,对 windows 式的路径无法处理,虽然在写方法时有考虑到这一点,加入了 option:slash 来预设,但是后来实在不知道如何去考虑它了。 其次,对出现一些特殊的绕来绕去的链接也是不成,如a/b/c/../../d之类的链接,也完全无法处理.... 但是木有办法,也只能将就着用了。 事实上,http://ruby-doc.org/stdlib-1.9.2/libdoc/fileutils/rdoc/FileUtils.html#method-i-mkdir_p里有现成的解决方案。

mkdir_p(list, options = {}) 
#Options: mode noop verbose
#Creates a directory and all its parent directories. For example,
#FileUtils.mkdir_p '/usr/local/lib/ruby'
#causes to make following directories, if it does not exist.
/usr
/usr/local
/usr/local/lib
/usr/local/lib/ruby
#You can pass several directories at a time in a list.
#Also aliased as: mkpath, makedirs

很明显,我试图重新发明轮子。花了大量的功夫,做出来的还是个不好用的瘪轮子。

基础最重要,得回头去肯 ruby-doc.org 了。

Unknow user #1 January 11, 2012

哈哈,有了这教训,对你查询官方文档习惯的养成有好处。

You need to Sign in before reply, if you don't have an account, please Sign up first.