Execute a Rake task from within migration? Execute a Rake task from within migration? ruby ruby

Execute a Rake task from within migration?


Yes there's a way to do that:

Rake::Task['your_task'].invoke

Update

Do not put rake inside the brackets, just the name of the task. You should set an ENV variable when running this:

In the console

FILE=somefile.text rake db:sistema:load_data

Calling it separately

FILE=somefile.text rake some:other:task:that:calls:it

This will be available in your tasks as ENV['file']


Note that if you call the Rake task with 'system', you need to check the process status afterwards and raise an exception if the Rake task failed. Otherwise the migration will succeed even if the Rake task fails.

You can check the process status like this:

if !($?.success?)  raise "Rake task failed"end

Invoking the rake task is a nicer option - it will cause the migration to fail if the Rake task fails.


You can execute a rake task from within a loaded Rails environment with either Rake::Task['namespace:task'].invoke or Rake::Task['namespace:task'].execute.

You can pass data to the task inside of the invoke or execute method. Example:

Rake::Task['namespace:task'].invoke(paramValue)

This param can be handled in the rake task as follows:

namespace :namespace do  desc "Example description."  task :task, [:param] => :environment do |t, args|    puts args[:param]    ...  endend

This can be executed on the console as:

bundle exec rake namespace:task[paramValue]

More info: https://medium.com/@sampatbadhe/rake-task-invoke-or-execute-419cd689c3bd