How to set class level variables in Rails initializer when using spring?

别来无恙 提交于 2020-01-24 23:47:56

问题


In my config/initializers/transaction_logger.rb I have the following code

# config/initializers/transaction_logger.rb
Transaction::Logger.logger = Transaction::Logger.new("log/transations.log")

Every time I change the code and run the tests I get:

 Failure/Error: delegate :info, :warn, :debug, :error, to: :logger

 Module::DelegationError:
   #<Class:Transaction::Logger>#error delegated to logger.error, but logger is nil: Transaction::Logger

I have to run spring stop and then re-run the test again (seems initializer's code to be executing after spring stop)

How should I set Transaction::Logger.logger to avoid this problem? Thanks


回答1:


As spring documentation says

So to avoid this problem, don't save off references to application constants in your initialization code.

Seems this can be related to setting up class variables too

I've moved setting up Transaction::Logger.logger into Transaction::Logger file

# app/core/transaction/logger.rb
class Transaction::Logger < Logger
...
end

Transaction::Logger.logger = Transaction::Logger.new("log/transactions.log")


来源:https://stackoverflow.com/questions/49948221/how-to-set-class-level-variables-in-rails-initializer-when-using-spring

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