Initializing a Global Instance of a Ruby Class

Hello,

I want to have an instance of a Ruby class I wrote initialized as a
single instance on app startup, and have that instance accessible from
my controllers. I assume this is simple, but have not been able to
figure this out.

Where do I initialize the class? And how can I access it from my
controllers?

I assume it is something like (env.rb…

‘’’
$myclassinstance = MyClass.new
‘’’
and then (foobar-controller.rb…
‘’’
def foo
@myvars = $myclassinstance.mymethod( params[:somevar] )
end
‘’’
Thanks for reading,

M

M P wrote:

I want to have an instance of a Ruby class I wrote initialized as a
single instance on app startup, and have that instance accessible from
my controllers. I assume this is simple, but have not been able to
figure this out.
:
$myclassinstance = MyClass.new

Global variables are not generally good practice. What you are
describing here is a singleton pattern. This is normally implemented as
a class method and class variable:

class MyClass
def self.the_single_instance
@@the_single_instance ||= self.new
end
end

Then use: MyClass.the_single_instance

The instance will be created on the fly if it doesn’t exist and you will
always get the same object each time. Note that this instance (and even
any global variable you set) will be local to the thread so each mongrel
instance (or whatever you use) will have it’s own copy so any data
related to the object that needs to be visible to all threads should be
held elsewhere (eg in the database, memcached, etc).

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs