2011-03-29 53 views
1

現在,我寫了這個邏輯..從創建訂單中的目錄獲取文件?

def get_file_names 
    @files = [] 
    Find.find("#{BACKUP_FILE_DIR}") do |path| 
     file_stat = File.stat path 
     @files << { 
     :name => File.basename(path,".*"), 
     :mtime => file_stat.mtime, 
     :path => path 
     } 
    end 
    @files.delete_at(0) 
    @files = @files.sort_by { |file| file[:mtime] } 
    @file_names = [] 
    @files.each do |f| 
     @file_names << [f[:name],f[:path]] 
    end 
    end 

我怎麼能改善這個方法?

+0

看到這個問題:http://stackoverflow.com/q/4739967/570156 – Elad 2011-03-29 13:23:39

+0

獲取文件夾名稱..文件夾內沒有文件名.. >> files_sorted_by_time = Dir ['/ db_backups']。sort_by {| f | File.ctime(f)} => [「/ db_backups」] – 2011-03-29 13:48:07

+2

嘗試Dir ['/ db_backups/*'] :) – Elad 2011-03-29 13:55:29

回答

0

你需要使用 「的ctime」 在文件::統計,而不是修改時間

mtime : time last modified 
ctime : time created 

試試這個:

# recursively collect file names based on ctime: 
# 
def get_file_names(dir) 
    Dir.chdir(dir) 
    Dir.entries(dir).each do |f| 
    # next if f == '.' 
    # next if f == '..' 
    next if f =~ /^\./ # ignore dot-files and dot-directories          

    full_filename = File.join(Dir.pwd , f) 

    if File.directory?(full_filename) 
     get_file_names(full_filename) 
    else 
     stat = File::Stat.new(full_filename) 
     @files_by_ctime[stat.ctime] ||= [] 
     @files_by_ctime[stat.ctime] << full_filename 
    end 
    end 
    Dir.chdir('..') 
end ; 1 

@files_by_ctime = {} 

get_file_names('/tmp') 

@files_by_ctime.keys.sort.each do |ctime| 
    puts "Created: #{ctime} : #{@files_by_ctime[ctime].inspect}" 
end ; 1