Ruby – How to run a rake task from Capistrano

capistranorakeruby

I already have a deploy.rb that can deploy my app on my production server.

My app contains a custom rake task (a .rake file in the lib/tasks directory).

I'd like to create a cap task that will remotely run that rake task.

Best Answer

A little bit more explicit, in your \config\deploy.rb, add outside any task or namespace:

namespace :rake do  
  desc "Run a task on a remote server."  
  # run like: cap staging rake:invoke task=a_certain_task  
  task :invoke do  
    run("cd #{deploy_to}/current; /usr/bin/env rake #{ENV['task']} RAILS_ENV=#{rails_env}")  
  end  
end

Then, from /rails_root/, you can run:

cap staging rake:invoke task=rebuild_table_abc