我在 config/initializers 中加了一个启动时执行的方法,它会调用 controllers/concerns 中某个 module 里的一些方法。这样做的目的是,项目中要用到一个全局变量,而生成这个全局变量需要几秒钟,为了避免反复生成它,就放到 initializers 中,让 rails 启动时生成一次,后面直接使用即可。实测完全正常。
但是在做 test 时出现了警告:
DEPRECATION WARNING: Initialization autoloaded the constants Const, Util, and Public.
Being able to do this is deprecated. Autoloading during initialization is going
to be an error condition in future versions of Rails.
Reloading does not reboot the application, and therefore code executed during
initialization does not run again. So, if you reload Const, for example,
the expected changes won't be reflected in that stale Module object.
These autoloaded constants have been unloaded.
Please, check the "Autoloading and Reloading Constants" guide for solutions.
(called from <main> at /home/thomas/rails/project/config/environment.rb:8)
Run options: --seed 18699
# Running:
.
Finished in 0.084160s, 11.8821 runs/s, 47.5284 assertions/s.
1 runs, 4 assertions, 0 failures, 0 errors, 0 skips
如果把 initializers 中那个启动时执行的方法去掉,一切正常。然而,如果不用 initializers,我想不出还有什么更好的办法来加载这个全局变量……
当然,出警告目前并不影响使用。但还是想知道有解决的办法吗?