Mongo and Sinatra on Heroku

I recently built a small app for Red Bull Records utilizing Sinatra on the backend. They wanted to collect some data from visitors to their site so I figured I would put my feet to the fire and try out my chops with Mongo for a very light solution. Hosting this all on Heroku provided a very quick implementation to get something up and running — except for figuring out how to hook in Mongo to the app.

Getting started

I chose to use Mongoid as the connector because of its similarity to ActiveRecord and defining of its collections.

Gems needed:

  • mongoid
  • mongo
  • bson_ext => makes for reading quicker
  • bson

Add ons needed:

  • MongoHQ

Communicating with Mongoid on Heroku

It took me a couple of searches to find the best/quickest method to getting this setup. Unfortunately, there were a lot of conflicting answers that never seemed to pan out. Finally, I stumbled on a solution that was a simple conditional check for an environment variable that Heroku passes to the app.

Utilizing the ENV[‘MONGOHQ_URL’] variable, I was quickly able to connect on production and also development to my Mongo database.

In your app, either your main app file or another config ruby file, you can simply do:

require 'mongoid'
configure do
    Mongoid.configure do |config|
       if ENV['MONGOHQ_URL']
        conn = Mongo::Connection.from_uri(ENV['MONGOHQ_URL'])
        uri = URI.parse(ENV['MONGOHQ_URL'])
        config.master = conn.db(uri.path.gsub(/^\//, ''))
      else
        name = "my_local_development_database"
        host = "localhost"
        config.master = Mongo::Connection.new.db(name)
      end
    end
end

No need to include a typical mongoid.yml file for configuration anymore as Heroku passes everything you need in that environment variable for the code to parse out the parts it needs to connect to the database. Pretty simple.

As this is my first step into the Mongo world, it was kind of exciting to step out of my comfort zone of front-end technologies and build an app that crosses the stacks.

Filed under: Code