diff --git a/lib/mongo/connection.rb b/lib/mongo/connection.rb index ee820d9..3e2da50 100644 --- a/lib/mongo/connection.rb +++ b/lib/mongo/connection.rb @@ -327,6 +327,22 @@ 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 11c8c1a..8a01478 100644 --- a/test/connection_test.rb +++ b/test/connection_test.rb @@ -82,6 +82,46 @@ class TestConnection < Test::Unit::TestCase end end + def test_db_from_uri_exists_no_options + begin + db_name = "_database" + + old_mongodb_uri = ENV['MONGODB_URI'] + ENV['MONGODB_URI'] = "mongodb://#{host_port}/#{db_name}" + con = Connection.from_uri + db = con.db_from_uri + assert_equal db.name, db_name + ensure + ENV['MONGODB_URI'] = old_mongodb_uri + end + end + + def test_db_from_uri_exists_options + begin + db_name = "_database" + + old_mongodb_uri = ENV['MONGODB_URI'] + ENV['MONGODB_URI'] = "mongodb://#{host_port}/#{db_name}?" + con = Connection.from_uri + db = con.db_from_uri + assert_equal db.name, db_name + ensure + ENV['MONGODB_URI'] = old_mongodb_uri + end + end + + def test_db_from_uri_exists_no_db_name + begin + 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 + ensure + ENV['MONGODB_URI'] = old_mongodb_uri + end + end + def test_server_version assert_match(/\d\.\d+(\.\d+)?/, @conn.server_version.to_s) end