到达目录时的目录步行调用方法

时间:2013-05-08 20:09:23

标签: ruby search methods directory directory-walk

尝试编写一个脚本,搜索特定文件的目录和子目录。我想知道一个或多个目录是如何调用方法的。

这是我尝试过的并且失败了:

def display_directory(path)
list = Dir[path+'/*'] 
return if list.length == 0

list.each do |f|     

  if File.directory? f #is it a directory?
    if File.directory?('config')
      puts "this is the config folder"
    end
    printf "%-50s %s\n", f, "is a directory:".upcase.rjust(25)
  else
    printf "%-50s %s\n", f, "is not a directory:".upcase.rjust(25)
  end
 end
end


start = File.join("**")
puts "Processing directory\n\n".upcase.center(30)
display_directory start

这就是我想要发生的事情。

        app
app/controllers
app/helpers
app/mailers
app/models
app/models/bugzilla
app/models/security
app/views
app/views/auth
app/views/calendar
app/views/layouts
app/views/step
app/views/step_mailer
app/views/suggestion
app/views/suggestion_mailer
app/views/task
app/views/user
bin
--------------------------------------
config <----------(call method foo)
config/environments
config/initializers
config/locales
--------------------------------------
db
db/bugzilla
db/migrate
db/security
lib
lib/tasks
log
public
public/images
public/javascripts
public/stylesheets
script
script/performance
script/process
--------------------------
test <---------(call method foobar)
test/fixtures
test/fixtures/mailer
test/functional
test/integration
test/performance
test/unit
--------------------------
vendor
vendor/plugins

2 个答案:

答案 0 :(得分:0)

相反

if File.directory?('config')

尝试

if f.path.include?('config')

但这适用于名称上有配置的每个目录。您可以放置​​一个更大的子字符串以进行更好的匹配。

此外,对于多线程块使用do..end和单行{..}使用ruby非常惯用。

答案 1 :(得分:0)

我找到了办法。这非常有效。我已经添加了一个方法来显示所提到的目录中的所有文件。

def special_dir(path)
  puts "------------------------------------"
  sp_path = Dir.glob(File.join(path,"*","**"))
  sp_path.each do |cf|
    puts "\t" + cf
  end
end

def walk(path)
  list = Dir[path+'/*'].reject{ |r| r['doc'] || r['tmp']}
    list.each do |x|
      path = File.join(path, x)
      if File.directory?(x)
        if x =~ /config/ or x =~ /test/  
          special_dir(x)
        else 
          puts "#{x}"
          walk(path)
        end
      else
        #puts x
      end
    end
  end

  start = File.join("**")

  walk start