问题描述
我正在写一项耙式任务,该任务在Rails/activerecord之外进行一些DB工作.
是否有一种方法可以获取database.yml?
中定义的当前环境的DB连接信息(主机,用户名,密码,DB名称)我想获得它,以便我可以使用它来像这样连接...
con = Mysql.real_connect("host", "user", "pw", "current_db")
推荐答案
从轨道内部您可以创建一个配置对象并从中获取必要的信息:
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"]
请参阅 documentation for rails :: configuration :: configuration :: >
这只是使用 yaml :: Load load load 您可以使用自己的数据库配置文件(database.yml)从铁路环境外部获取信息:
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
返回哈希中的连接配置:
=> {:adapter=>ADAPTER_NAME, :host=>HOST, :port=>PORT, :database=>DB, :pool=>POOL, :username=>USERNAME, :password=>PASSWORD}
as tpett在他们的评论中注释:该解决方案解释了database.yml和来自环境变量DATABASE_URL的配置的解决方案.DATABASE_URL.
问题描述
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")
推荐答案
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.