Rails How to Run Rake Task

Rails how to run rake task

You can run Rake tasks from your shell by running:

rake task_name

To run from from Ruby (e.g., in the Rails console or another Rake task):

Rake::Task['task_name'].invoke

To run multiple tasks in the same namespace with a single task, create the following new task in your namespace:

task :runall => [:iqmedier, :euroads, :mikkelsen, :orville] do
# This will run after all those tasks have run
end

How to run rake tasks from console?

Running your Rake tasks requires two steps:

  1. Loading Rake
  2. Loading your Rake tasks

You are missing the second step.

Normally this is done in the Rakefile, but you have to do it manually here:

require 'rake'
Rails.application.load_tasks # <-- MISSING LINE
Rake::Task['my_task'].invoke

how to run rake task using rails migration

Migrations are really just Ruby files following a convention, so if you want to run a rake task inside of them you can just call the Rake class.

class ExampleMigration < ActiveRecord::Migration[5.0]
def change
Rake::Task['task_for_log'].invoke
end
end

However, migration files should be used specifically to handle the database schema. I would rethink how you are approaching the problem for a better solution. For example, you could run a SQL statement that updates your log attributes instead of calling a rake task.

class ExampleMigration < ActiveRecord::Migration[5.0]
def change
execute <<-SQL
UPDATE logs SET log_date = created_at WHERE log_date IS NULL
SQL
end
end

References:

  • Rails how to run rake task
  • https://edgeguides.rubyonrails.org/active_record_migrations.html

How to run a rake task by command line in rails

  1. Run rake -T -A from your Rails home directory to see all the tasks that rake knows about. Yours must be in that list for rake to run it.
  2. By default, in a Rails app, rake looks in the lib/tasks directory and its subdirectories for your .rake files. Check that. (I suspect this is the problem.)

Run Rake task programmatically with specified environment

I managed to find a solution to this. I believe the reason is that .invoke will not always invoke the task, but it will first determine whether it is necessary. Given that rake db:create is run on several occasions within the same task, .invoke deems the subsequent invocations as unnecessary and therefore does not run them. For the desired behaviour, .execute should be used instead.

# remove db:create from the list of rake tasks in order to override it
db_create = Rake.application.instance_variable_get('@tasks').delete('db:create')

namespace :db do
task :create do
if Rails.env == "development"
Rails.env = "secondary_development"
Rake::Task["db:create"].execute # execute rather than invoke
end

# Reset the Rails env to 'development', otherwise it remains as 'secondary_development', which is not what we want (or move this above the if)
Rails.env = "development"
db_create.execute
end
end


Related Topics



Leave a reply



Submit