Created
August 22, 2012 17:04
-
-
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
saved my ass, thanks