带有急切初始化的单例
我的 X 类需要很多时间来初始化自身。我想使该类成为单例,并在 Rails 应用程序启动时强制创建它。
我已经创建了单例:
class X @@instance = nil def self.instance if @@instance.nil? @@instance = X.new puts 'CREATING' end return @@instance end private_class_method :new end
问题是每次我使用这个类时,我都会在日志中看到“CREATING”。我尝试将类的创建放在 initializers
目录中,但它也不起作用。
I have class X that takes much time to initialize itself. I want to make that class singleton and force its creation when rails application starts.
I've made the singleton:
class X @@instance = nil def self.instance if @@instance.nil? @@instance = X.new puts 'CREATING' end return @@instance end private_class_method :new end
The problem is that every time I use this class I see 'CREATING' in logs. I've tried to put creation of class in initializers
directory but it doesn't work either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是开发环境中的 Rails 不会缓存类,并且每个请求都会重新加载应用程序代码。
The problem was that Rails in development environment doesn't cache classes and application code is reloaded every request.