且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使Ruby的Find.find遵循符号链接?

更新时间:2023-11-19 13:30:58

对于其他人,我最终使用 路径名

code> 和下面的递归代码:

pre $ def $ all_files_under(* paths)
paths .flatten!
paths.map! {| p | Pathname.new(p)}
files = paths.select {| p | p.file? }
(路径 - 文件).each do | dir |
档案<< all_files_under(dir.children)
end
files.flatten
end


I have a file hierarchy and some of the sub-directories are relative symlinks. I am using Ruby's Find.find to crawl through these dirs and find some specific files. However it's not looking into any directory which is a symlink (it follows files which are symlinks).

Looking at the source code it seems the problem is because it's using File.lstat(file).directory? to test if something is a directory. This returns false for symlinks but File.stat.directory? returns true.

How can I make Find.find follow symlinks, short of monkey patching it to use File.stat instead of File.lstat?

For anyone else watching, I ended up using Pathname and the following recursive code:

def all_files_under(*paths)
  paths.flatten!
  paths.map! { |p| Pathname.new(p) }
  files = paths.select { |p| p.file? }
  (paths - files).each do |dir|
    files << all_files_under(dir.children)
  end
  files.flatten
end