Singleton with eager initialization

Posted by jesper on Stack Overflow See other posts from Stack Overflow or by jesper
Published on 2011-01-09T20:30:39Z Indexed on 2011/01/09 20:54 UTC
Read the original article Hit count: 200

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.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about singleton