Running code after Rails is done loading?

a 夏天 提交于 2019-12-05 21:28:13

问题


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!


回答1:


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



回答2:


Add your code in the initializer directory.

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




回答3:


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)



来源:https://stackoverflow.com/questions/10972450/running-code-after-rails-is-done-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!