List audiobooks and/or music based on directories: Ruby Version

Alec Jacobson

November 05, 2009

weblog/

I previously posted a bash script to count and print plain text and html listings of a directory: intended for displaying audiobook and music libraries. I recently tried to use the bash script on a large directory and it stalled because sed can't handle large input. Here's a ruby version that does the same thing:
#!/usr/bin/ruby -w
usage = "Usage: list [filename] [directory] 
If filename ends with .html then output will be html,
else output will be plain text."
if not ARGV[0] or not ARGV[1]
  puts usage
elsif not File.directory? ARGV[1]
  puts "list: #{ARGV[1]} is not a directory"
  puts usage
else
  dir = ARGV[1]
  # should be quoted?
  plain = (`ls -1 "#{dir}"/*`+"\n")
  if(ARGV[0] =~ /.html$/i)
    plain = plain.split("\n")
    author_count = plain.find_all{|line| line=~/:$/}.length
    title_count = plain.find_all{|line| line=~/[^:]$/}.length
    body = plain.collect do |line|
      line.gsub(
        /(.*)([^:])$/,'      \1\2</br>').gsub(
        /^\s*$/,'    </div>').gsub(
        /.*\/(.*):$/,'    <h3>\1</h3>'+"\n"+'    <div class="books">')
    end
    output = "<html>
  <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/> 
  <head> 
    <style type='text/css'>
      body {
        font : 10pt verdana;
        background: white;
        width: 95%
      }
      h2 {
        margin: 15px 0px 5px 0px;
      }
      h3 {
        margin: 15px 0px 5px 0px;
      }
      .books {
        border: 1px solid #dddddd;
        padding: 5px 5px 5px 10px;
        background: #eeeeff;
      }
    </style>
  </head>
  <body>
    <h2>#{title_count} titles and #{author_count} authors</h2>
  #{body.join("\n")}</div>
  </body> 
</html>"
  else
    output = plain;
  end
  File.open(ARGV[0], 'w') {|f| f.write(output) }
end