简体   繁体   English

Ruby:将新字段添加到YAML文件

[英]Ruby: add new fields to YAML file

I've been searching around for a bit and couldn't find anything that really helped me. 我一直在寻找一些东西,找不到任何真正对我有帮助的东西。 Especially because sometimes things don't seem to be consistant. 尤其是因为有时情况似乎不一致。

I have the following YAML that I use to store data/ configuration stuff: 我有以下用于存储数据/配置内容的YAML:

---
global:
  name: Core Config
  cfg_version: 0.0.1
  databases:
    main_database:
      name: Main
      path: ~/Documents/main.reevault
      read_only: false    

    ...

I know how to update fields with: 我知道如何使用以下方式更新字段:

cfg = YAML.load_file("test.yml")
cfg['global']['name'] = 'New Name'
File.open("test.yml", "w"){ |f| YAML.dump(cfg, f) }

And that's essentially everybody on the internet talks about. 基本上,这是互联网上每个人都在谈论的话题。 However here is my problem: I want to dynamically be able to add new fields to that file. 但是,这是我的问题:我想动态地能够向该文件添加新字段。 eg under the "databases" section have a "secondary_db" field with it's own name, path and read_only boolean. 例如,在“数据库”部分下有一个“ secondary_db”字段,它具有自己的名称,路径和read_only布尔值。 I would have expected to do that by just adding stuff to the hash: 我本来希望通过向哈希中添加一些东西来做到这一点的:

cfg['global']['databases']['second_db'] = nil
cfg['global']['databases']['second_db']['name'] = "Secondary Database"
cfg['global']['databases']['second_db']['path'] = "http://someurl.remote/blob/db.reevault"
cfg['global']['databases']['second_db']['read_only'] = "true"
File.open("test.yml", "w"){ |f| YAML.dump(cfg, f) }

But I get this error: 但是我得到这个错误:

`<main>': undefined method `[]=' for nil:NilClass (NoMethodError)

My question now is: how do I do this? 我现在的问题是:我该怎么做? Is there a way with the YAML interface? YAML接口有办法吗? Or do I have to write stuff into the file manually? 还是我必须手动将内容写入文件? I would prefer something via the YAML module as it takes care of formatting/ indentation for me. 我希望通过YAML模块进行操作,因为它可以为我处理格式/缩进。

Hope someone can help me. 希望可以有人帮帮我。

Yo have to initialize cfg['global']['database']['second_db'] to be a hash not nil. 您必须将cfg['global']['database']['second_db']初始化为哈希,而不是nil。 Try this cfg['global']['database']['second_db'] = {} 试试这个cfg['global']['database']['second_db'] = {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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