开发者

Singleton with eager initialization

开发者 https://www.devze.com 2023-02-03 02:50 出处:网络
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 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 singl开发者_高级运维eton:

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.


The problem was that Rails in development environment doesn't cache classes and application code is reloaded every request.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号