Running Rails code/initializers but not via Rake

时间秒杀一切 提交于 2019-12-10 18:26:36

问题


I keep running into a recurring issue with my application. Basically, I have certain code that I want it to run when it first starts up the server to check whether certain things have been defined e.g. a schedule, particular columns in the database, existence of files, etc. and then act accordingly.

However, I definitely don't want this code to run when I'm starting a Rake task (or doing a 'generate', etc. For example, I don't want the database fields to be checked under Rake because the Rake task might be the migration to define the fields. Another example, I have a dynamic schedule for Resque but I don't want to load that when starting the Resque workers. And so on and so forth...

And I definitely need the Rake tasks to be loading the environment!

Is there any way of determining how the application has been loaded? I do want to run the code when its loaded via 'rails server', Apache/Passenger, console, etc. but not at other times.

If not, where or how could you define this code to ensure it is only executed in the manner described above?


回答1:


The easiest way is checking some environment variable in your initialization code with something like

if ENV['need_complex_init']
  do_complex_init     
end

and running application with need_complex_init=1 rails s



来源:https://stackoverflow.com/questions/18202862/running-rails-code-initializers-but-not-via-rake

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