2015-02-09 73 views
1

我试图在YAML配置文件中保存一些变量。红宝石,写入YAML文件,与阵列

酷!

然而,当我尝试救出来,我在Ruby中得到一个错误:

undefined method `[]=' for false:FalseClass (NoMethodError) 

我的功能应该(在我的头上至少)是:

  1. 是否配置文件存在如果没有,只需创建一个空白的。
  2. 现在我们知道它的存在,它YAML.open
  3. 设置新/覆盖键/值对
  4. 重新写入文件

但是,我得到上述错误。

我是新来的红宝石(PHP的家伙在这里),告诉我在哪里我太傻了,请:)

def write_to_file(path_to_file, key, value, overwrite = true) 

    if !File.exist?(path_to_file) 
     File.open(path_to_file, 'a+') 
    end 

    config_file = YAML.load_file(path_to_file) 

    config_file[key] = value 

    File.open(path_to_file, 'w') { |f| YAML.dump(config_file, f) } 
    # I tried this commented code below too, same error.. 
    # {|f| f.write config_file.to_yaml } 


end 

回答

4

的问题是,你创建一个空文件。

YAML.load('') #=> false 

只需设置config_file为空哈希如果是false:和YAML解析器空字符串返回false

config_file = YAML.load_file(path_to_file) || {} 
+0

好胳肢我侧身,..这真是棒极了。所有我的其他VARS现在正在保存,我可以在另一个功能中选择它们......你是先生..是我的英雄..和老师。 – Beertastic 2015-02-09 12:02:18