John
John

Reputation: 1323

rake task is not calling. from the controller action in rails.

I have created a rake task in the file called att_rec_for_emp.rake . in this file i have the following task.

  task hello(parameter): :environment do

  p "{parameter}"

  end

how can i call this rake task in the controller action by passing parameters?

i have an action like this

   def call_task
     emp = Employee.first
     Rake::Task[ 'att_rec_for_emp:hello("hello world")' ].invoke
     redirect_to :root , :notice => "message fine" 
   end

and in config/initialisers/rake.rb i have the following statement.

  Rake.load_rakefile Rails.root.join(  'lib','tasks','att_rec_for_emp.rake' )

but still the task is not executing. getting the error

   Don't know how to build task 'att_rec_for_emp:hello'

Upvotes: 0

Views: 436

Answers (2)

madcow
madcow

Reputation: 2633

I think I got it working. Tweak from here.

Here's what I did:

lib/tasks/att_rec_for_emp.rake

task :hello, [:parameter] => :environment do |t, args|
  p "#{args[:parameter]}"
end

app/controllers/your_controller.rb

Rake::Task.clear
YourAppName::Application.load_tasks

class YourController < ApplicationController
  def call_task
    Rake::Task[:hello].reenable
    Rake::Task[:hello].invoke('hi world')
  end
end

You could also put those first two lines (above YourController class definition) in an initializer.

Note: Your approach of loading the Rake file in an initializer should work too but my setup is a little different. I have my entire lib directory loaded in application.rb.

config/application.rb

config.autoload_paths += Dir["#{config.root}/lib"]

Hope that helps!

Upvotes: 2

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34318

Try adding this line to your controller:

YourAppName::Application.load_tasks

Or, change the directory name from initialisers to initializers.

Upvotes: 0

Related Questions