Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A Better Mongoid Sinatra configuration implementation. Using settings hash for db options sucks!
# This is a modification of the blogpost on how to use Mongoid and Sinatra.
# Here is the original blogpost http://www.garrensmith.com/2010/09/11/Mongoid-sinatra.html
# The modification lets you use Mongoid 3.0 with the new Moped driver
# The new Moped driver uses the Sessions component to define the MongoDB connection rather
# than the Mongo::Connection.new that is used in the case of the default Ruby driver.
# Moped::Session.new vs Mongo::Connection.new
# Mongoid.load!(yaml_config.yml) is used to build the config hash. Alternatively, the hash can
# be built manually by using Mongoid.config {|config| ...} syntax. The config.sessions hash
# contains the session information. The config hash has three main components: the session
# name (by default, its :default), the hosts that run the MongoDB instances (specified by
# :hosts) and the database to connect (specified by :database).
# Username and password, if present should also be defined via respective keys.
require 'sinatra'
require 'mongoid'
configure do
Mongoid.configure do |config|
config.sessions = {
:default => {
:hosts => ["localhost:27017"], :database => "my_db"
}
}
end
end
class User
include Mongoid::Document
field :name
field :age
end
get '/' do
User.find.count # returns the total number of users.
end

saved my ass, thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment