Ruby를 공부하면서 뭘 만들어 볼까 고민하다가 평소 MP3파일이 많아 이것을 리스트 할수 있는 프로그램을 필요해서 함 만들어 보았다

User Story는 다음과 같다.

(1) 사용자가 MP3파일이 있는 제일 상위 폴더를 입력한다.

(2) 입력한 제일 상위 폴더를 기준으로 그 안에 있는 모든 하위 폴더에 있는 MP3파일 이름을 저장한다.

(3) 저장된 MP3파일이름 리스트를 파일로 쓴다.

해당 프로그램의 주요 함수는 filewrite, subdir 함수 이다.

filewrite는 말그대로 MP3파일리스트를 파일에 저장하는 역활을 하는 함수이고

subdir은 루트 디렉토리를 기준으로 하위폴더를 순회하며 MP3파일이름을 저장하는 함수이다. Tree형태로 이루어진 폴더구조로 재귀함수 구조이다. 아래는 filewrite 함수와 subdir 함수내용이다.

subdir의 재귀호출를 유심히 보면 된다. 

def filewrite()
    file = File.new(@lname,"w")
    file.puts "<BABO MP3 FILE LIST>"
    file.puts "작성일 : " + DateTime.now.strftime("%Y-%m-%d %H:%M:%S")
    file.puts "TOTAL FILE COUNT : #{@@filenamelist.length}"
    file.puts "\n\n"
    @@filenamelist.each do |mpff|
          file.puts "#{mpff}" 
    end
    file.close
  end
def subdir(dir, indent)
    files = []
    dirs =  [] 
     # 하위디렉토리 검색

    Dir.foreach(dir) do |ff|
        path = File.join(dir, ff)
        # Note: this doesn't follow symlinks
        if File.directory?(path)
            dirs.push(ff) if  ff[0] != ?.
        else
            files.push(ff)
        end
    end

    dirs.sort!
    files.sort!
    fileIndent = indent + (dirs.length > 0 ? LinedIndent: WSIndent)
    

     #MP3 File 추출
    files.each do |ff|
        if ff.include?("mp3")
          @@filenamelist.push(ff)
          puts "#{fileIndent}#{ff}" 
        end
    end

    return if dirs.length == 0

    if dirs.length > 1
        nextIndent = indent + LinedIndent
        thisIndent = indent + DirIndent
        dirs[0..-2].each do |dd|
            puts "#{thisIndent}#{dd}/"
            subdir(File.join(dir, dd), nextIndent)
        end
    end
    puts "#{indent + DirIndent}#{dirs[-1]}/"
    subdir(File.join(dir, dirs[-1]), indent + WSIndent)
  end 

해당 루비프로그램의 결과는 다음과 같다.
 

사용자 삽입 이미지

http://serapian.pe.kr/trackback/102 관련글 쓰기