add Connection#db_from_uri to round out MONGODB_URI support

This commit is contained in:
John Bintz 2012-06-05 17:40:51 -04:00
parent 9be394b623
commit 11a5d8bd53
2 changed files with 56 additions and 0 deletions

View File

@ -327,6 +327,22 @@ module Mongo
DB.new(db_name, self) DB.new(db_name, self)
end 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. # Drop a database.
# #
# @param [String] name name of an existing database. # @param [String] name name of an existing database.

View File

@ -82,6 +82,46 @@ class TestConnection < Test::Unit::TestCase
end end
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 def test_server_version
assert_match(/\d\.\d+(\.\d+)?/, @conn.server_version.to_s) assert_match(/\d\.\d+(\.\d+)?/, @conn.server_version.to_s)
end end