How do I run rake tasks within my rails application

后端 未结 5 839
青春惊慌失措
青春惊慌失措 2020-12-24 08:47

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

相关标签:
5条回答
  • 2020-12-24 09:26
    require 'rake'
    RailsApp::Application.load_tasks
    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
    

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

    0 讨论(0)
  • 2020-12-24 09:39

    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

    0 讨论(0)
  • 2020-12-24 09:40

    Have you tried `rake ts:reindex`?

    0 讨论(0)
  • 2020-12-24 09:43

    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
    
    0 讨论(0)
  • 2020-12-24 09:46

    I had this same issue and couldn't get the accepted answer to work in my controller with a Rails 4 project due to a load file error. This post gave me a working solution:

    def restart_search
       require 'rake'
       spec = Gem::Specification.find_by_name 'thinking-sphinx'
       load "#{spec.gem_dir}/lib/thinking_sphinx/tasks.rb"
       Rake::Task["ts:stop"].execute
       Rake::Task["ts:start"].execute
       respond_to do |format|
         format.js { head :ok }
       end
    end
    
    0 讨论(0)
提交回复
热议问题