I’ve developed a handful of Rails (3.x) applications which all used MongoDB as the persistence layer. In fact, I’ve yet to build a SQL backed Rails application during my “day job”. Thus far I’ve preferred Mongoid vs. MongoMapper, primarily because of the documentation. Although, I haven’t gone back to look at MongoMapper in almost a year…but at this point, I don’t have a need to change.
Typically with Mongoid, you’ll have a mongoid.yml file that has your database configuration. That’s really super when you only use Mongoid to interact with your database. However, if you end up using another library/gem that needs to work with your database you’ll have to duplicate your database configuration. NOT! Being a star developer (you know you are), you’ll come up with some solution so you don’t have to copy your database configuration around to multiple files.
I ran into this situation when I began using Qu. Qu is a library for “queueing and processing background jobs”. It’s easy to use, has a dandy API and works with either MongoDB or Redis. It might be worth mentioning here thatBrandon Keepers, the creator of Qu, worked for Ordered List which was recently acquired by GitHub.
Anyways, back to my solution for not duplicating database configuration. I’ve recently started using the settingslogic gem on my Rails project to manage my application configuration. I have a “application.yml” file that now contains my database configuration. Using settingslogic is not a requirement, in fact Rails has a built-in method for dealing with application configuration, so use what you like.
Once I had my database configuration in a file, I setup two initializers: one for Mongoid and one for Qu. The best way I found was to create a MongoDB URI formatted string. Check out the following gist:
Now Mongoid and Qu use the same database configuration settings and it all comes from one file. Of course, you might want Mongoid and Qu to use different configuration settings, but hopefully you can see the benefit to my approach.
Now that I’ve checked the time, I’m going to get 5 hours of sleep. So, like a chef, I’m cooked.