auralbee
auralbee

Reputation: 8841

Invoke rake task from ActiveRecord observer

Can I do the following?

def ModelObserver < ActiveRecord

   def after_save
     Rake::Task[name].invoke
   end

end

At the moment, this returns the following error:

Don't know how to build task 'name'

Any idea?

Upvotes: 1

Views: 621

Answers (4)

Adrian Serafin
Adrian Serafin

Reputation: 7715

In Rails3 if you still want to call rake task like this:

Rake::Task[name].invoke

you have to put

[Application].load_tasks

before invoke command, where application is your application name. For example I had to put

Ead::Application.load_tasks

Upvotes: 2

samuil
samuil

Reputation: 5081

Consider using delayed job or similar plugin to handle background execution. In observer (or controller) just notify background job daemon, that it should take care of some action, instead of running this task directly.

Upvotes: 2

hurikhan77
hurikhan77

Reputation: 5930

I suppose you have to load the Rake environment first, and the Rakefile. I would not try to invoke the fullblown command line to do that. You probably need to use "import" as can be found in the Rake API

Upvotes: 0

shingara
shingara

Reputation: 46914

Use the system command :

def ModelObserver < ActiveRecord

   def after_save
     system "rake #{name}"
   end

end

Upvotes: 3

Related Questions