Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running files in a directory recursively using ruby

I'm working on script right now which has to run each ruby script in a directory and its subfolders.

e.g.

run-all.rb
- scripts
  - folder1
    - script1.rb
    - script2.rb
  - folder2
    - script3.rb
    - script4.rb

As the server is a Windows server I would normally use a batch file but the head dev insists everything must be done in ruby as some members have Macs and may not understand Windows Batch Files.

As the question may have given away, my knowledge of Ruby is very basic.

like image 521
Macha Avatar asked Mar 27 '09 12:03

Macha


2 Answers

Depends what you mean by "run". To just execute the code that is in each script within the same ruby process, this will do the trick:

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

But it you want to run each script in it's own ruby process, then try this:

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

Just put the either of these in the contents of run-all.rb and the run ruby run-all.rb form the command line.

like image 188
pjb3 Avatar answered Oct 13 '22 16:10

pjb3


Something like this should probably work:

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
like image 33
ddccffvv Avatar answered Oct 13 '22 18:10

ddccffvv