简体   繁体   中英

Write content into yml file from given hash in Ruby

I have a yml file which contains some information about the databases settings. I need to crate a file which took the content of key and create a file.

like, my yml file:

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

When I load this yml file and try to write individual file information in new yml file that saved in wrong manner.

I want to write content in new file like

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'] so return me hash

{"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"}}

So I want to write this content in new yml file like

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

I have tried like this:

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

So output like this

---
- :client-1.domaine.net: www.client-1.domaine.net/index.html/xxxxxx
  :fef: 12

try applying the method 'to_yaml' to the hash instead of array of hashes. You will get it right

This is your code

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

Do this

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

and check. Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM