back to list

Mongo and Sinatra on Heroku

  July 05, 2012 — written by Chris Sloan | 0 comments »

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 in: Geekery, Interweb | permalink

0 shared their opinion. ADD YOURS »

Add your opinion here

March 2017
S M T W T F S
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31  
top of page
 

where you can find me

RailsConf 2010

Flickr Github Working with Rails Linked In

my twitter tweets

follow me