Controlling iTunes with Ruby (alternate take)

Here’s a different version of the same playlist-generating script. This one uses rb-appscript rather than the built-in Scripting Bridge. (Raw source here.)

#!/usr/bin/env ruby

# Run to create a playlist named "today’s tunes". The playlist is 
# populated with tracks selected because the first character of their
# names begins with a randomly selected letter or digit. For example, 
# my list today begins like this:
#  Galang
#  Gamma Ray
#  Gary Stomp
#  Gear

require appscript
include Appscript

PLAYLIST_NAME = "today’s tunes"

def main
  todays_tunes = make_empty_playlist
  tracks = tracks_beginning_with(some_random_character, all_songs)
  tracks.each do | track |
    track.duplicate(:to => todays_tunes)
  end
end

def make_empty_playlist
  ensure_no_playlist(PLAYLIST_NAME)
  p = ITUNES.make(:new => :playlist, :at => LIBRARY,
                  :with_properties => { :name => PLAYLIST_NAME })
  p.shuffle.set(true)
  p
end

def tracks_beginning_with(letter, tracks)
  tracks.get.find_all do | track |
    name = track.name.get
    name = phrase_tail(name) if starts_with_qualifier?(name)
    /^#{letter}/i =~ name
  end
end

def ensure_no_playlist(name)
  p = LIBRARY.playlists[name]
  p.delete if p.exists
end

def all_songs
  LIBRARY.playlists[’Library‘].tracks
end

def some_random_character
  possibilities = (’a‘..’z‘).to_a + (’0‘..’9‘).to_a
  possibilities[rand(possibilities.length)]
end

# Works with either a NSCFString or a string.
# TODO: Change tests to indicate that?
def starts_with_qualifier?(name)
  name =~ /^thes/i || name =~ /^ans/i || name =~ /^as/i
end

def phrase_tail(name)
  name.gsub(/^w+s+/, ‘)
end

ITUNES = app(’iTunes‘)
LIBRARY = ITUNES.sources[’Library‘]

if $0 == __FILE__
  main
end

Leave a Reply

You must be logged in to post a comment.