Apr 3

Passing around arguments in rake tasks

Category: Development,Rails

So I had the need to pass arguments from one rake task to another.  This is easy to do from the command line, but gets a bit tricking when its being called from within another rake task.  So here is the task that is being called:

  1 namespace :database do
  2   desc %{Dump DB to create restore data in case of error}
  3   task :dump, :tables, :needs  => [:setup] do |t, args|
  4     filename = "#{DB_NAME}#{'-'+args.tables.values.join('-') unless args.tables.nil?}-#{DB_DUMP_TIME}.sql.gz"
  5     puts "Dumping the database to '#{filename}'"
  6 
  7     cmd = ""
  8     cmd << "echo 'SET AUTOCOMMIT=0;'|gzip> #{filename};"
  9     cmd << "echo 'SET FOREIGN_KEY_CHECKS=0;'|gzip>> #{filename};"
 10     cmd << "mysqldump -u #{DB_USER} -p'#{DB_PASSWORD}' "
 11     cmd << "-h #{DB_HOST} #{DB_NAME} "
 12     cmd << "--tables #{args.tables.values.join(' ')} " unless args.tables.nil?
 13     cmd << "|gzip>> #{filename};"
 14     cmd << "echo 'SET FOREIGN_KEY_CHECKS=1;'|gzip>> #{filename};"
 15     cmd << "echo 'COMMIT;'|gzip>> #{filename};"
 16     cmd << "echo 'SET AUTOCOMMIT=1;'|gzip>> #{filename};"
 17 
 18     if system(cmd)
 19       puts "Successfully ran databse:dump to restore run:"
 20       puts "rake database:reload DB_DUMP_TIME='#{DB_DUMP_TIME}'"
 21     else
 22       puts "rake database:dump was unsuccessful"
 23     end
 24   end

So this task is used to dump the database for our app. I added the ability to pass in an optional hash to allow it to only dump the specified tables. Here are the important lines to note.

task :dump, :tables, :needs  => [:setup] do |t, args|

The “tables” argument specifies what arguments are being passed in. The “t” and “args” block defines the task and the arguments. Your “tables” hash is now available through “args” values.

Now when I call this task from within another rake task, I can do something like this.

tables = {:table1 => 'users', :table2 => 'roles'}
Rake::Task["database:dump"].invoke(tables)

Note, I define the hash outside of the invoke because it is used by two other tasks, but it could be directly passed to the task as an argument.

No comments

No Comments

Leave a comment