views:

32

answers:

3

I want to run a method, on the startup of the rails server. It's a model method.

I tried using config/initializers/myfile.rb, but the method was invoked during migrations, so it SELECTed from a nonexistant table.

Tried environment.rb also, but the class does not exist yet (and will probably have the same problem with migrations)

I don't know where to put that method, so it'll run only on server startup and not during migrations.

+1  A: 

Try putting your method call in boot.rb, in the run method after the Rails::initializer call. I don't have rails in front of me right now because I'm at work but I think that the whole environment should be loaded by that point and you can run methods on the framework.

AndrewKS
My model class is not accessible from that file (or i don't know how to access it).
Alistra
+2  A: 

There is no way to avoid this from my understanding. You can put the initializer code that relies on the new table in a rescue block to quiet things down so others can run migrations.

abdollar
+2  A: 

There are some things you could do to actually improve this a bit. The issue is that you are running this code when rake loads your environment, but you really only want to run this when the environment is loaded by an instance of your web server. One way to get around this is to set a value when rake loads your environment, and when that value is set, to not execute your initializer code. You can do this as follows:

task :environment => :disable_initializer

task :disable_initializer do
   ENV['DISABLE_INITIALIZER_FROM_RAKE'] = 'true'
end

#In your initializer:

ENV['DISABLE_INITIALIZER_FROM_RAKE'] || MyModel.method_call
Pete
works very nice, thx
Alistra