#! /usr/local/bin/ruby require 'rubygems' require 'rbosa' require_gem 'activerecord' iTunes = OSA.app('iTunes') exit if iTunes.nil? ActiveRecord::Base.establish_connection( :adapter => 'mysql', :username => 'root', :host => 'localhost', :password => 'secret', :database => 'iTunes', :encoding => 'utf8' ) # Overload the Track class that comes out of the OSA call to iTunes. # Overload to_s for nice printing, and to_h to put it into ActiveRecord more easily. module OSA module ITunes class Track def to_s "(#{database_id}) #{artist} - #{name}" end def to_h {:database_id => database_id.to_i, :artist => artist, :name => name} end end end end # Database model for our track. Yeah, this class and the class coming out of # OSA are both named 'Track', whatever. class Track < ActiveRecord::Base attr_accessor :database_id def before_create write_attribute(:id, database_id) write_attribute(:play_count, 1) end end # Blow away any previous results Track.delete_all("true") # Do your thing. while true iTunes.next_track current_track = iTunes.current_track p current_track.to_s if Track.exists?(current_track.database_id) Track.increment_counter(:play_count, current_track.database_id) else Track.create(current_track.to_h) end sleep(1) end