Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
mongo initializer to load config from database.yml, authenticate if needed and ensure indexes are created
development: &global_settings
database: textual_development
host: 127.0.0.1
port: 27017
test:
database: textual_test
<<: *global_settings
production:
host: hostname
database: databasename
username: username
password: password
<<: *global_settings
config = YAML.load_file(Rails.root + 'config' + 'database.yml')[Rails.env]
MongoMapper.connection = Mongo::Connection.new(config['host'], config['port'], {
:logger => Rails.logger
})
MongoMapper.database = config['database']
if config['username'].present?
MongoMapper.database.authenticate(config['username'], config['password'])
end
Dir[Rails.root + 'app/models/**/*.rb'].each do |model_path|
File.basename(model_path, '.rb').classify.constantize
end
MongoMapper.ensure_indexes!
if defined?(PhusionPassenger)
PhusionPassenger.on_event(:starting_worker_process) do |forked|
# if using older than 0.6.5 of MM then you want database instead of connection
# MongoMapper.database.connect_to_master if forked
MongoMapper.connection.connect_to_master if forked
end
end

martijn commented Jun 30, 2010

This Gist seems to get linked from a lot of places so I feel I should mention that most of the code from the mongo.db example above is now integrated in MongoMapper. This means you can replace the entire initalizer with the following two lines:

config = YAML.load_file(Rails.root + 'config' + 'database.yml')
MongoMapper.setup(config, Rails.env, { :logger => Rails.logger })

This gives you logging through the Rails logger to boot, which is useful during development.

Yet another option:

config = YAML.load_file(Rails.root.join('config', 'database.yml'))
MongoMapper.setup(config, Rails.env, { :logger => (Rails.env.development? ? Rails.logger : nil) })
Owner

jnunemaker commented Jul 16, 2010

Yeah, this gist is old. Thanks for comment with the update. I typically just throw rails logger on there no matter what as the log level for the driver is just debug which won't show in prod anyway.

martijn commented Jul 16, 2010

It was pointed out to me on the Google group that you don't have to parse the database.yml yourself either. This wil suffice:

MongoMapper.setup(Rails.configuration.database_configuration, Rails.env, :logger => Rails.logger)

Assigning the Rails logger in all environments has worked fine for me, too.

Super-cool. Thanks!

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