probably at the beach
probably at the beach

Reputation: 15207

How do I initialize an instance variable in a ruby Singleton?

I have a ruby class that is using the Singleton pattern. I would like to initialize an instance variable as soon as the class is create (i.e instance is called). Where is the best place to do this?

require 'singleton'

class SingletonTest
  include Singleton
  @my_var # where / how should I initialize this
end

Thanks

Upvotes: 1

Views: 1992

Answers (1)

Stefan Kanev
Stefan Kanev

Reputation: 3040

You should do that in the constructor, i.e.

class MySingleton
  include Singleton

  def initialize
    @something = 42
  end
end

You're guaranteed to have the constructor called before .instance returns.

Upvotes: 8

Related Questions