Skip to content

Instantly share code, notes, and snippets.

@kgrz
Created August 22, 2012 17:04
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kgrz/3427564 to your computer and use it in GitHub Desktop.
Save kgrz/3427564 to your computer and use it in GitHub Desktop.
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
@Arthraim
Copy link

saved my ass, thanks

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