Permalink
Browse files

Provide database connection settings as a URL.

  • Loading branch information...
1 parent 22e4727 commit 89357c8f834f638210d004ae9426aaa052dd519b @glenngillen glenngillen committed with tenderlove Jun 28, 2011
View
22 activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
@@ -58,6 +58,8 @@ def self.establish_connection(spec = nil)
when Symbol, String
if configuration = configurations[spec.to_s]
establish_connection(configuration)
+ elsif spec.is_a?(String) && hash = connection_url_to_hash(spec)
+ establish_connection(hash)
else
raise AdapterNotSpecified, "#{spec} database is not configured"
end
@@ -81,6 +83,26 @@ def self.establish_connection(spec = nil)
end
end
+ def self.connection_url_to_hash(url)
+ config = URI.parse(url)
+ adapter = config.scheme
+ adapter = "postgresql" if adapter == "postgres"
+ spec = { :adapter => adapter,
+ :username => config.user,
+ :password => config.password,
+ :port => config.port,
+ :database => config.path.sub(%r{^/},""),
+ :host => config.host }
+ spec.reject!{ |key,value| value.nil? }
+ if config.query
+ options = Hash[query.split("&").map{ |pair| pair.split("=") }].symbolize_keys
+ spec.merge!(options)
+ end
+ spec
+ rescue URI::InvalidURIError
+ return nil
+ end
+
class << self
# Returns the connection currently associated with the class. This can
# also be used to "borrow" the connection to do database work unrelated
View
11 activerecord/test/cases/adapter_test.rb
@@ -60,6 +60,17 @@ def test_collation
assert_equal @connection.show_variable('collation_database'), @connection.collation
end
+ def test_connect_with_url
+ begin
+ ar_config = ARTest.connection_config['arunit']
+ url = "mysql://#{ar_config["username"]}@localhost/#{ar_config["database"]}"
+ ActiveRecord::Base.establish_connection(url)
+ assert_equal ar_config['database'], ActiveRecord::Base.connection.current_database
+ ensure
+ ActiveRecord::Base.establish_connection 'arunit'
+ end
+ end
+
def test_show_nonexistent_variable_returns_nil
assert_nil @connection.show_variable('foo_bar_baz')
end

0 comments on commit 89357c8

Please sign in to comment.