views:

24

answers:

2

I'm running Rails 3, and I've got several controllers that all do something like the following:

@db = Mongo::Connection.new.db(MONGOID_CONFIG['database'])

I don't want to have multiple connections to the database, so the natural thing would seem to be to wrap @db in some singleton that's initialized when I start the app. My question is, how to do that?

My first thought was to use a helper, but I'm told that those are only recommended for generating view stuff, and obviously views shouldn't be directly accessing the database. What else is there? Write a plugin? :)

+1  A: 

first of all, you can write an helper to put, for example, in application_controller.rb, so there's no problem about views (well, view helper normally goes in app/helpers/).

otherwise, you can write the following command and put it in config/initializers/mongo_db.rb:

$db = Mongo::Connection.new.db(MONGOID_CONFIG['database'])

the file will be loaded at boot, $db represents a global variable, so it's avaiable to the entire application (Views included, though), by the way you'll use it only in the appropriate places, right? ;-P

apeacox
I like the initializer idea. Apologies for my Ruby newbieness, but what would be the syntax for declaring a global function there instead of a variable? (I want to use a function wrapper to maintain the connection instance and reconnect if necessary.)
Trevor Burnham
you can create a very simple class that wraps the connection exposing some ad-hoc method ;)
apeacox
+1  A: 

If you're using Mongoid (I assume you might because of your constant being named MONGOID_CONFIG), you can use @db = Mongoid.master.connection to get the Mongo::Connection that's connected to the master db server.

Andreas
Thanks, I just discovered that. In fact, you can use `Mongoid.database`, bypassing the connection entirely.
Trevor Burnham