Techioz Blog

コントローラーでrakeタスクを実行する

概要

コントローラーで rake タスクを実行したいと考えています。これを行う方法はありますか?

解決策

私は ddfreynee に同意しますが、必要なものがわかっている場合に備えて、コードは次のようになります。

require 'rake'

Rake::Task.clear # necessary to avoid tasks being loaded several times in dev mode
Sample::Application.load_tasks # providing your application name is 'sample'

class RakeController < ApplicationController

  def run
    Rake::Task[params[:task]].reenable # in case you're going to invoke the same task second time.
    Rake::Task[params[:task]].invoke
  end

end

代わりに、初期化子で ‘rake’ と .load_tasks を要求できます。