Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running code after Rails is done loading?

I have a periodic task that needs to execute once a minute (using delayed_job). I would like for Rails to automatically queue it up as soon as it's finished loading, if one such task isn't already present in the system.

What is a good place for me to run some code right at the end of the entire Rails boot flow? Someone suggested config/environments/development.rb (or other environment), but delayed_job give me ActiveRecord issues when I queue up jobs from there.

I consulted http://guides.rubyonrails.org/initialization.html, and there doesn't seem to be a clear location for that kind of code either.

Is this kind of post-deployment setup to be done perhaps externally to my app's code, maybe through rake or some other means? Any suggestions?

Thank you!

like image 468
Alexandr Kurilin Avatar asked Jun 10 '12 21:06

Alexandr Kurilin


3 Answers

Regarding http://guides.rubyonrails.org/initialization.html, sorry, we're working hard to rewrite it. For your problem, I would try with config.after_initialize in your application.rb

def after_initialize(&block)
  ActiveSupport.on_load(:after_initialize, :yield => true, &block)
end
like image 168
Oscar Del Ben Avatar answered Oct 20 '22 13:10

Oscar Del Ben


Add your code in the initializer directory.

http://guides.rubyonrails.org/configuring.html#using-initializer-files

like image 38
Ismael Avatar answered Oct 20 '22 14:10

Ismael


You have two options really

1) add it into initializers directory and this should be ok.

2) add it at the very end of application.rb, this is less clean but it will have things like initializers ready at this point ;p so if 1) fails because of AR problems do 2)

like image 2
Jakub Oboza Avatar answered Oct 20 '22 12:10

Jakub Oboza