n8gard
n8gard

Reputation: 1970

Create a single, custom, globally available object in a rails app

I am having a very difficult time finding the answer to this. I want to create a custom class (this I know how to do) and have it get instantiated--one instance--that is globally accessible from within my application. I am looking to centralize and abstract some code and use this globally-available object as an interface. I can't believe how weird this is to figure out.

I need to have models, etc., available from within this object.

Help is appreciated.

I am running Rails 3.2.8.

Upvotes: 0

Views: 189

Answers (2)

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

You probably want a Singleton...

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/singleton/rdoc/Singleton.html

However, that will only be available to that apps process. If you run multiple app servers (ie. multiple thin instances or Passenger) each will have it's own instance.

If you need something truly global you'll have to look into other options.

Upvotes: 0

Andrew
Andrew

Reputation: 43123

Any model that you put in app/models will be autoloaded by Rails, so you can stick a custom model there.

The class will be available throughout your app, so whether you can just use class methods or not is up to you. If you want it to be a singleton, see this helpful article.

Lastly, if you need the model to instantiate in some specific way, just put it in an initializer. Any file in config/initializers will be run once as the app boots up.

Upvotes: 1

Related Questions