你可以在Rails中获得数据库用户名,密码,数据库名称?

我正在写一个Rake任务,它可以使一些数据库在Rails / ActiveRecord之外工作。

有没有办法获取当前环境的数据库连接信息(主机,用户名,密码,数据库名称)在database.yml定义?

我想得到它,所以我可以用它来连接像这样…

 con = Mysql.real_connect("host", "user", "pw", "current_db") 

从rails内部可以创build一个configuration对象并从中获取必要的信息:

 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"] 

有关详细信息,请参阅Rails :: Configuration的文档 。

这只是使用YAML :: load从数据库configuration文件( database.yml )加载configuration,您可以使用它自己从rails环境外部获取信息:

 require 'YAML' info = YAML::load(IO.read("database.yml")) print info["production"]["host"] print info["production"]["database"] ... 

布赖恩在上面的评论中的答案值得多一点曝光:

 >> 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 

以散列forms返回连接configuration:

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

正如tpett在他们的评论中指出的那样:这个解决scheme将合并来自database.yml和环境variablesDATABASE_URL

老问题,但这是我的第一站查找如何做到这一点,所以我认为这可能会帮助别人。 我通常在主目录中有.my.cnf文件。 因此,在我的database.ymlconfiguration文件中使用'parseconfig'gem和一些ERB语法意味着我有了一个dynamic的文件,可以感觉良好的检查到源代码控制,也简化了部署(在我的情况下)。 还要注意常用套接字的列表,这使得将应用程序移动到可能具有不同Unix套接字path的不同操作系统更容易。

 <% require 'parseconfig' c=ParseConfig.new('../../.my.cnf') %> mysqlevn: &mysql adapter: mysql username: <%= c.params['client']['user'] %> password: <%= c.params['client']['password'] %> host: localhost socket: <%= [ '/var/run/mysqld/mysqld.sock', '/var/lib/mysql/mysql.sock', '/tmp/mysqld.sock', '/tmp/mysql.sock'].detect { |socket| File.exist?(socket) } %> production: database: app_production <<: *mysql development: database: app_development <<: *mysql # Do not set this db to the same as development or production. test: database: app_test <<: *mysql 

ref: http : //effectif.com/articles/database-yml-should-be-checked-in