views:

252

answers:

2

When I run a rake task for an application that uses Models defined in a plugin I get an Uninitialized Constant error, but when I run the model process, with script/runner, that is fired in the rake task then the job runs fine?

Is there some difference between script/runner that loads all my plugins that doesn't happen when I fire up a rake task even though it is being passed an environment?

+1  A: 

Your rake task needs to be dependent upon :environment. That will spin up your app's environment and give you access to your models, etc.

Eg

desc "Make DB Views"
task :views => [:environment] do |t|
# your task's code

end
Larry K
That's the thing though, we do have the the environment being passed in that way, that's what makes it so odd.
railsninja
A: 

You need to specify that your Rake task requires the environment to be loaded:

task :your_task => :environment do |t| ...

or

task :your_task => [:environment] do |t| ...

or

task :your_task, :param1, :param2, :needs => :environment do |t, args| ...

or

task :your_task, :param1, :param2, :needs => [:environment] do |t, args| ...

If you did specify this, then there is another problem. I think one common source of errors is due to the fact that the plugins are loaded inside a namespace called Rails::Plugin. So if you defined a class called Foo in your plugin, then the Rake task needs to reference it as Rails::Plugin::Foo instead of simply Foo.

If this does not solve your problem then try to add puts "Check" on the first line of the plugin's init.rb file, and make sure that Check is displayed when you run your rake task. If it is, then your plugin is being loaded, but perhaps it fails silently after that.

One last thing: maybe you are trying to use the plugin outside the task, for example at the beginning of your Rake file, in some initialization code? If so, then it will fail because the plugins only get loaded when the task is executed (when the environment is loaded).

Hope this helps.

MiniQuark