使用Ruby递归地运行目录中的文件

11
我正在编写一个脚本,需要运行指定文件夹及其子文件夹中的所有 Ruby 脚本。
例如:
run-all.rb
- scripts
  - folder1
    - script1.rb
    - script2.rb
  - folder2
    - script3.rb
    - script4.rb

由于服务器是 Windows 服务器,我通常会使用批处理文件,但头部开发人员坚持所有内容必须在 Ruby 中完成,因为有些成员可能使用 Mac 并且不了解 Windows 批处理文件。

正如问题可能已经透露的那样,我的 Ruby 知识非常基础。

2个回答

28

这取决于你所说的"运行"是什么意思。如果只是在同一Ruby进程中执行每个脚本中的代码,可以使用以下方法:

Dir["scripts/**/*.rb"].each{|s| load s }

但是如果您想在单独的 Ruby 进程中运行每个脚本,请尝试以下方法:

Dir["scripts/**/*.rb"].each{|s| puts `ruby #{s}` }

只需将以下任意一个内容放入run-all.rb文件的内容中,然后在命令行中运行ruby run-all.rb即可。


1

像这样应该可以工作:

def process_directory(basedir)
puts basedir
Find.find(basedir.chomp) do |path|
    if FileTest.directory?(path)
        if File.basename(path)[0] == ?.
            Find.prune       # Don't look any further into this directory.
        else
            next
        end
    else
        puts path
    end
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接