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
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With