Can You Get DB Username, Pw, Database Name In Rails?


Answer :

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

config   = Rails.configuration.database_configuration host     = config[Rails.env]["host"] database = config[Rails.env]["database"] username = config[Rails.env]["username"] password = config[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"] ... 

Bryan's answer in the comment above deserves a little more exposure:

>> Rails.configuration.database_configuration[Rails.env] => {"encoding"=>"unicode", "username"=>"postgres", "adapter"=>"postgresql", "port"=>5432, "host"=>"localhost", "password"=>"postgres", "database"=>"mydb", "pool"=>5} 

ActiveRecord::Base.connection_config 

returns the connection configuration in a hash:

=> {:adapter=>ADAPTER_NAME, :host=>HOST, :port=>PORT,      :database=>DB, :pool=>POOL, :username=>USERNAME,      :password=>PASSWORD}  

As tpett remarked in their comment: this solution accounts for merging the configuration from database.yml and from the environment variable DATABASE_URL.


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable