From 9d4429221edfd47f02b283300e810155f36072db Mon Sep 17 00:00:00 2001 From: John Bintz Date: Wed, 6 Jun 2012 11:37:04 -0400 Subject: [PATCH] move functionality to Connection#db, set up default database name to use when absolutely nothing is provided --- lib/mongo/connection.rb | 25 ++++++++----------------- test/connection_test.rb | 8 ++++---- 2 files changed, 12 insertions(+), 21 deletions(-) diff --git a/lib/mongo/connection.rb b/lib/mongo/connection.rb index 3e2da50..cddd99f 100644 --- a/lib/mongo/connection.rb +++ b/lib/mongo/connection.rb @@ -34,6 +34,7 @@ module Mongo DEFAULT_HOST = 'localhost' DEFAULT_PORT = 27017 + DEFAULT_DB_NAME = 'test' GENERIC_OPTS = [:ssl, :auths, :pool_size, :pool_timeout, :timeout, :op_timeout, :connect_timeout, :safe, :logger, :connect] CONNECTION_OPTS = [:slave_ok] @@ -312,7 +313,13 @@ module Mongo # @return [Mongo::DB] # # @core databases db-instance_method - def db(db_name, opts={}) + def db(db_name=nil, opts={}) + if !db_name && uri = ENV['MONGODB_URI'] + db_name = uri[%r{/([^/\?]+)(\?|$)}, 1] + end + + db_name ||= DEFAULT_DB_NAME + DB.new(db_name, self, opts) end @@ -327,22 +334,6 @@ module Mongo DB.new(db_name, self) end - # Return the database specified in ENV['MONGODB_URI'] - # - # @param [String] uri the uri to use - # @param [Hash] opts options to be passed to the DB constructor. - # - # @return [Mongo::DB] - # - # @core databases db_from_uri-instance_method - def db_from_uri(uri=ENV['MONGODB_URI'], opts={}) - if db_name = uri[%r{/([^/\?]+)(\?|$)}, 1] - DB.new(db_name, self, opts) - else - raise ArgumentError.new("No database name found in #{uri}") - end - end - # Drop a database. # # @param [String] name name of an existing database. diff --git a/test/connection_test.rb b/test/connection_test.rb index 8a01478..5f7a98d 100644 --- a/test/connection_test.rb +++ b/test/connection_test.rb @@ -89,7 +89,7 @@ class TestConnection < Test::Unit::TestCase old_mongodb_uri = ENV['MONGODB_URI'] ENV['MONGODB_URI'] = "mongodb://#{host_port}/#{db_name}" con = Connection.from_uri - db = con.db_from_uri + db = con.db assert_equal db.name, db_name ensure ENV['MONGODB_URI'] = old_mongodb_uri @@ -103,7 +103,7 @@ class TestConnection < Test::Unit::TestCase old_mongodb_uri = ENV['MONGODB_URI'] ENV['MONGODB_URI'] = "mongodb://#{host_port}/#{db_name}?" con = Connection.from_uri - db = con.db_from_uri + db = con.db assert_equal db.name, db_name ensure ENV['MONGODB_URI'] = old_mongodb_uri @@ -115,8 +115,8 @@ class TestConnection < Test::Unit::TestCase old_mongodb_uri = ENV['MONGODB_URI'] ENV['MONGODB_URI'] = "mongodb://#{host_port}/" con = Connection.from_uri - - assert_raise ArgumentError do con.db_from_uri end + db = con.db + assert_equal db.name, Mongo::Connection::DEFAULT_DB_NAME ensure ENV['MONGODB_URI'] = old_mongodb_uri end