Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run rake tasks within my rails application

What I want to do:

In a model.rb, in after_commit, I want to run rake task ts:reindex

ts:reindex is normally run with a rake ts:index

like image 218
fivetwentysix Avatar asked Sep 09 '10 09:09

fivetwentysix


People also ask

How do I create a run Rake task?

Go to Websites & Domains and click Ruby. After gems installation you can try to run a Rake task by clicking Run rake task. In the opened dialog, you can provide some parameters and click OK - this will be equivalent to running the rake utility with the specified parameters in the command line.

Where do I put Rake tasks?

rake extension and are placed in Rails. root/lib/tasks . You can create these custom rake tasks with the bin/rails generate task command. If your need to interact with your application models, perform database queries and so on, your task should depend on the environment task, which will load your application code.

How do I see all Rake tasks?

You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing rake --tasks . Each task has a description, and should help you find the thing you need.


2 Answers

If you wish this rake code to run during the request cycle then you should avoid running rake via system or any of the exec family (including backticks) as this will start a new ruby interpreter and reload the rails environment each time it is called.

Instead you can call the Rake commands directly as follows :-

require 'rake'

class SomeModel <ActiveRecord::Base

  def self.run_rake(task_name)
    load File.join(RAILS_ROOT, 'lib', 'tasks', 'custom_task.rake')
    Rake::Task[task_name].invoke
  end
end

Note: in Rails 4+, you'll use Rails.root instead of RAILS_ROOT.

And then just use SomeModel.run_rake("ts:reindex")

The key parts here are to require rake and make sure you load the file containing the task definitions.

Most information obtained from http://railsblogger.blogspot.com/2009/03/in-queue_15.html

like image 127
Steve Weet Avatar answered Nov 15 '22 15:11

Steve Weet


This code automagically loads the Rake tasks for your Rails application without you even knowing how your application is named :)

class MySidekiqTask
  include Sidekiq::Worker

  def perform
    application_name = Rails.application.class.parent_name
    application = Object.const_get(application_name)
    application::Application.load_tasks
    Rake::Task['db:migrate'].invoke
  end
end
like image 40
snrlx Avatar answered Nov 15 '22 14:11

snrlx