views:

1615

answers:

1

I'm writing a rake task that does some DB work outside of Rails/ActiveRecord.

Is there a way to get the DB connection info (host, username, password, DB name) for the current environment as defined in database.yml?

I'd like to get it so I can use it to connect like this...

con = Mysql.real_connect("host", "user", "pw", "current_db")
+17  A: 

From within rails you can create a configuration object and obtain the necessary information from it:

config   = Rails::Configuration.new
host     = config.database_configuration[RAILS_ENV]["host"]
database = config.database_configuration[RAILS_ENV]["database"]
username = config.database_configuration[RAILS_ENV]["username"]
password = config.database_configuration[RAILS_ENV]["password"]

See the documentation for Rails::Configuration for details.

This just uses YAML::load to load the configuration from the database configuration file (database.yml) which you can use yourself to get the information from outside the rails environment:

require 'YAML'
info = YAML::load(IO.read("database.yml"))
print info["production"]["host"]
print info["production"]["database"]
...
Robert Gamble
In more recent Rails, you don't need to create the configuration, you can get it via `Rails.configuration`
Bryan Larsen