rails是否有内置的方法将database.yml config转换为数据库URL?

时间:2018-04-12 08:39:42

标签: ruby-on-rails postgresql

我有一个标准的postgresql database.yml配置。我需要生成一个数据库URL,以便在其他地方使用相同的参数。我认为rails有一种方法或者?

development:
  adapter: postgresql
  encoding: utf8
  host: localhost
  username: postgres
  password: postgres
  pool: 10
  reaping_frequency: 10
  connect_timeout: 5 # sec
  checkout_timeout: 5 # sec
  template: template0
  schema_search_path: "public,extensions"

PS。我发现这个与https://gist.github.com/pricees/9630464

的方式相反

2 个答案:

答案 0 :(得分:1)

也许这会有所帮助?

Get DATABASE_URL from config hash

你传递一个哈希(字符串或符号键,无关紧要),它会给你一个URL:

>> c = YAML.load_file('/path/to/config/database.yml')
=> {"development"=>{"adapter"=>"mysql2", "database"=>"myapp_development", "username"=>"root", "password"=>"password", "encoding"=>"utf8"}, "test"=>{"adapter"=>"mysql2", "database"=>"myapp_test", "username"=>"root", "password"=>"password", "encoding"=>"utf8"}, "production"=>{"adapter"=>"mysql2", "database"=>"myapp", "username"=>"myapp", "password"=>"XXX", "encoding"=>"utf8"}, "cucumber"=>{"adapter"=>"mysql2", "database"=>"myapp_cucumber", "username"=>"root", "password"=>"password", "encoding"=>"utf8"}}
>> DatabaseUrl.to_active_record_url c['development']
=> "mysql2://root:password@127.0.0.1/myapp_development?encoding=utf8"

答案 1 :(得分:1)

不 - 没有内置方法。

ActiveRecord中的连接处理由ActiveRecord::ConnectionHandling处理,它将配置作为哈希和URL并合并它们。

因此,您可以获取URL并将其转换为配置对象:

ActiveRecord::ConnectionAdapters::ConnectionSpecification::ConnectionUrlResolver.new(url)

由于它不需要框架,因为它将配置作为哈希传递给连接适配器,因此没有其他方法可以采用另一种方式。