How to run custom rake task via capistrano 3?

kpblc picture kpblc · May 23, 2014 · Viewed 9.7k times · Source

which way, i can run rake commands via capistrano on remote server.

for example i have a lib/task/reparse.rake with some methods

desc "it's take csv file, makes some changes and fill db with this info"
task :example1 => :environment do
  require 'csv'
  rows_to_insert = []
  # some actions
  # ...
end

on local server all is fine - i just run rake reparse:example1 and it's work(fill db correctly). so question is - how can i run this command on real hosting, after deploy?

i'am using rails 4.1 + capistrano 3.

P.S. examples from site not work for me How do I run a rake task from Capistrano?

if i try cap production rake:invoke task=reparse:land it fails with:

cap aborted!
Don't know how to build task 'rake:invoke'

some fixes

namespace :somenamespace do
  task :runrake do  
    on roles(:all), in: :sequence, wait: 5 do      
      within release_path do
        execute :rake, ENV['task'], "RAILS_ENV=production"
      end 
    end
  end
end

with such way it begin to execute via

cap production somenamespace:runrake task=custom_task_file:custom_method1

Answer

Kukunin picture Kukunin · Jan 15, 2015

Based on the capistrano/rails gem: https://github.com/capistrano/rails/blob/master/lib/capistrano/tasks/migrations.rake

namespace :somenamespace do
  task :runrake do
    on roles(:all) do
      within release_path do
        with rails_env: fetch(:rails_env) do
          execute :rake, ask :task
        end
      end 
    end
  end
end