Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on rails, run a method on server start 2.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.

like image 752
Alistra Avatar asked Apr 21 '26 20:04

Alistra


1 Answers

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
like image 54
Pete Avatar answered Apr 24 '26 09:04

Pete