pcrawfor

Paul Crawford

"My clever take on the world."

Rake tasks are fun!

Ok so of course the second I posted my rake task I found an excellent blog article talking about rake tasks that has a better implementation of my own task :) Err the blog has an excellent article on rake and his own creation sake (used to access rake tasks at a system level so that they need not be copied into each rails project independently) here.

(for anyone wanting the quick answer here is the much more elegant impl. of the db version task which is now in rails trunk and has been since about June of last summer) desc "Returns the current schema version" task :version => :environment do puts "Current version: " + ActiveRecord::Migrator.current_version.to_s end


Not to be out done I have a new rake task for you that I am finding useful, along with the annotate_models plugin this one allows a quick view of a table structure without firing up your mysql client.


desc – Describe the table listing column name and type


desc "Describe database table structure" task :describe => :environment do unless ENV.include?('table') && !ENV['table'].blank? raise "usage: rake db:desc table=table_name" end table = ENV['table'] ActiveRecord::Base.establish_connection(RAILS_ENV.to_sym) result = ActiveRecord::Base.connection.execute("describe #{table}") puts "table #{table}" result.each do |row| puts "#{row[0]} - #{row[1]}" end end


Usage: rake db:desc table=table_name


One other useful tidbit contained in this task is the parameter passed into the task, I picked this up from a Jay Field’s article here.

The key is that the parameters to the rake task are passed in the ENV hash and have to be accessed accordingly. I’ve also taken Jay’s approach of verifying the parameter and raising an exception if it is not provided to give the user usage info.