2017-01-03 67 views
0

我有一個yml文件,其中包含有關數據庫設置的一些信息。我需要創建一個帶有密鑰內容並創建文件的文件。將內容寫入Ruby中的給定散列的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 
+0

你的嘗試解決方案與這個問題有什麼關係? –

+0

我試過這樣的東西 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 但這看起來不像'rails.'的'database.yml'。 –

+0

其實我試過簡單的例子 –

回答

0

嘗試應用該方法 'to_yaml' 到哈希,而不是散列的數組。你會得到它的權利

這是你的代碼

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 

做這個

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[0].to_yaml 
           ^^^ 
end 

和檢查。 希望它有幫助