Exercise-2-1
require 'rubygems'
require 'active_record'
require 'utils'

# this is init_db from utils.rb
# check out all the source through subversion
#
# http://social.itp.nyu.edu/dedi/svn/rails.itp
#
# username: itp with the usual password
#

#def init_db
#  logfile = '/Users/dedi/Documents/itp/awd/examples/week2/shows.log'#
#
#  # let's warm up the database goodness
#  ActiveRecord::Base.logger = Logger.new(logfile)
#  ActiveRecord::Base.colorize_logging = false
#  ActiveRecord::Base.establish_connection(
#    :adapter => 'sqlite3',
#    :database => 'db/shows.db' )
#end
init_db() # kick off ActiveRecord

class Show < ActiveRecord::Base
  belongs_to :rating
  belongs_to :genre
end

class Rating < ActiveRecord::Base
  has_many :shows
end
class Genre < ActiveRecord::Base
  has_many :shows
end

if __FILE__ == $0
  command = ARGV[0]

  case command
  when 'help'
    usage =  %Q{USAGE: ruby tv.rb command parameters\n\n}
    usage << %Q{migrate\t\t- make db changes with migrations\n}
    usage << %Q{list\t\t- list shows\n}
    usage << %Q{day\t\"day"\t- list shows on day\n}
    usage << %Q{name\t"name"\t- find by name\n}
    usage << %Q{rate\t"name"\t- add rating to show\n}
    usage << %Q{genre\t"name"\t- add genre to show\n}
    usage << %Q{add\t"name" "description" "day"\t- add a show\n}
    print usage

  when 'name'
    @shows = Show.find_by_name ARGV[1]
    list_shows(@shows)

  when 'add'
    @show = Show.create :name => ARGV[1], :description => ARGV[2],
      :day => to_day_id(ARGV[3])

  when 'day'
    @shows = Show.find_by_day to_day_id(ARGV[1])
    list_shows(@shows)

  when 'rate'
    @show = Show.find_by_name ARGV[1]
    @rating = Rating.find_by_audience(ARGV[2])

    @show.rating = @rating
    puts "Rating added" if @show.save

  when 'genre'
    @show = Show.find_by_name ARGV[1]
    @genre = Genre.find_by_name(ARGV[2])

    @show.genre = @genre
    puts "Genre added" if @show.save 

  when 'migrate'
    ActiveRecord::Base.logger = Logger.new(STDERR)
    ActiveRecord::Base.colorize_logging = true
    migrate(ENV["VERSION"] ? ENV["VERSION"].to_i : nil)

  else
    @shows = Show.find :all, :order => 'day asc'
    list_shows(@shows)
  end
end

link download