【发布时间】:2017-05-17 11:01:08
【问题描述】:
我有一个yml 文件,其中包含有关数据库设置的一些信息。我需要创建一个包含密钥内容的文件并创建一个文件。
喜欢,我的 yml 文件:
db_info.yml
databases:
database1: # This would be first database
development:
adapter: mysql2
host: localhost
database: dev1
password: root
username: root
encoding: utf8
test:
adapter: mysql2
host: localhost
database: dev1_test
username: root
password: root
host: localhost
database2: # This would be second database
development:
adapter: mysql2
host: localhost
encoding: utf8
database: dev
password: root
username: root
test:
adapter: mysql2
host: localhost
database: dev_test
username: root
password: root
host: localhost
当我加载此yml 文件并尝试将单个文件信息写入以错误方式保存的新yml 文件时。
我想在新文件中写入内容
new_file.yml
config_file = Rails.root.join('config', 'multiple_database.yml')
file = YAML.load(ERB.new(File.new(config_file).read).result)
file['databases']['database1'] 所以把哈希还给我
{"development"=>{"adapter"=>"mysql2", "host"=>"localhost", "database"=>"dev1", "password"=>"root", "username"=>"root", "encoding"=>"utf8"}, "test"=>{"adapter"=>"mysql2", "host"=>"localhost", "database"=>"dev1_test", "password"=>"root", "username"=>"root", "encoding"=>"utf8"}}
所以我想把这个内容写在新的yml文件中
development:
adapter: mysql2
host: localhost
database: dev1
password: root
username: root
test:
adapter: mysql2
host: localhost
database: dev1_test
username: root
password: root
host: localhost
我试过这样:
array_of_hashes = [{:"client-1.domaine.net"=>"www.client-1.domaine.net/index.html/xxxxxx", :fef => 12}]
File.open("lib/yamlfile.yml","w") do |file|
file.write array_of_hashes.to_yaml
end
这样输出
---
- :client-1.domaine.net: www.client-1.domaine.net/index.html/xxxxxx
:fef: 12
【问题讨论】:
-
你尝试的解决方案与这个问题有什么关系?
-
我尝试过类似这样的 array_of_hashes = [{:"client-1.domaine.net"=>"www.client-1.domaine.net/index.html/xxxxxx", :fef => 12}] File.open("lib/yamlfile.yml","w") 做 |file| file.write array_of_hashes.to_yaml end 但这似乎不像
database.yml那样rails。 -
其实我用简单的例子试过
-
数组:
[{:"client-1.domaine.net"=>"www.client-1.domaine.net/index.html/xxxxxx", :fef => 12}]与您帖子的前 90% 有什么关系?你说要重新格式化db_info.yml,然后换个话题。您谈到定义数据库配置,如adapter: mysql2,然后再次转换主题。我不明白你的问题。 -
@TomLord,对此深表歉意,我正在处理应用程序并将代码粘贴到此处,但我直接在
console上尝试了一些操作并粘贴到此处。情况有所不同。