How do I run rake tasks within my rails application

fivetwentysix picture fivetwentysix · Sep 9, 2010 · Viewed 10.5k times · Source

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

Answer

Steve Weet picture Steve Weet · Sep 9, 2010

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