如何让Ruby FileList获取没有名称的文件,比如Windows上的.htaccess

时间:2010-03-29 10:07:22

标签: ruby

我想在我的文件系统中搜索扩展名为.template的任何文件。

以下内容适用于除.htaccess.template

以外的所有内容
FileList.new(File.join(root, '**', '*.template')).each do |file|
    # do stuff with file
end 

因为windows不喜欢无名文件,grrrr

如何在Windows上运行此功能?这段代码在Linux上运行良好....

2 个答案:

答案 0 :(得分:6)

怎么样

Dir.glob([".*.template", "*.template"])

答案 1 :(得分:1)

假设这里的FileList是来自rake的FileList类,那么问题出在Ruby的基础Dir类(由FileList使用)不匹配的文件开头.通配符*。 rake.rb的相关部分是

# Add matching glob patterns.
def add_matching(pattern)
  Dir[pattern].each do |fn|
    self << fn unless exclude?(fn)
  end
end

下面是一个丑陋的黑客,它会覆盖add_matching以包含以.开头的文件。希望其他人能够提出更优雅的解决方案。

class Rake::FileList
  def add_matching(pattern)
    files = Dir[pattern]
    # ugly hack to include files starting with . on Windows
    if RUBY_PLATFORM =~ /mswin/
      parts = File.split(pattern)
      # if filename portion of the pattern starts with * also
      # include the files matching '.' + the same pattern
      if parts.last[0] == ?*
        files += Dir[File.join(parts[0...-1] << '.' + parts.last)]
      end
    end    
    files.each do |fn|
      self << fn unless exclude?(fn)
    end
  end
end

更新:我刚刚在Linux上对此进行了测试,并且不包括以.开头的文件。例如如果我的目录/home/mikej/root包含2个子目录ab,其中每个子目录包含first.template.other.template,那么

Rake::FileList.new('home/mikej/root/**/*.template')
=> ["/home/mikej/root/a/first.template", "/home/mikej/root/b/first.template"]

所以我会仔细检查Linux上的行为,并确认没有其他因素导致行为上的差异。