# Initializing a Global Instance of a Ruby Class

**URL:** <https://www.ruby-forum.com/t/initializing-a-global-instance-of-a-ruby-class/134364>\
**Category:** Rails\
**Created:** [April 10, 2008, 5:49am UTC](https://www.ruby-forum.com/t/initializing-a-global-instance-of-a-ruby-class/134364 "2008-04-10T05:49:16Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![M\_P](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/c67d28/32.png) [@M\_P](https://www.ruby-forum.com/u/M_P)\
**Post date:** [April 10, 2008, 5:49am UTC](https://www.ruby-forum.com/t/initializing-a-global-instance-of-a-ruby-class/134364/1 "2008-04-10T05:49:16Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![M\_P](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/c67d28/32.png) [@M\_P](https://www.ruby-forum.com/u/M_P)\
**Post date:** [April 10, 2008, 10:10am UTC](https://www.ruby-forum.com/t/initializing-a-global-instance-of-a-ruby-class/134364/2 "2008-04-10T10:10:34Z")

</div>

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).
