Search

August 2, 2012

Ruby Play List Copier, Take 1

So I finally got back to my Ruby play list project. The next mini-goal would be to parse a play list file and print out the converted file names. I created a PlayListEntry class and a PlayList class and things were moving along very well:

require 'taglib'

class PlayListEntry

  SEPARATOR = " - "
  SUFFIX = ".mp3"

  attr_accessor :source, :dest, :dest_dir

  def initialize(source)
    @source = source
    determine_dest
  end

  def set_dest_dir(dest_dir)
    @dest_dir = dest_dir
  end

  def determine_dest
    TagLib::FileRef.open(@source) do |fileref|
      tag = fileref.tag
      if not tag then
        puts "No tags for #{source}"
        next
      end
      basename = tag.artist + SEPARATOR + tag.album + SEPARATOR +
        tag.track.to_s + SEPARATOR + tag.title + SUFFIX
      if dest_dir then
        @dest = File.join(dest_dir, basename)
      else
        @dest = basename
      end
    end
  end

end

class PlayList

  attr_accessor :playlist, :entries

  def initialize(playlist)
    @playlist = playlist
    read_playlist
  end

  def read_playlist
    @entries = []

    File.open(playlist) do |file|
      file.readlines.each do |line|
        line = line.strip
        if line.empty? or line[0] == '#' then
          next
        end
        if File.exists?(line) then
          @entries << PlayListEntry.new(line)
        else
          puts "File #{line} does not exist"
        end
      end
    end

  end

end

playlist = PlayList.new(ARGV[0])
playlist.entries.each {|x| puts x.dest }

That’s when I realized I am pretty much just doing Java style code in Ruby. I need to change this up and try to make it more Ruby-like. Possibilities include using modules or code blocks. We’ll see where it goes.