Reputation: 711
I'm trying to save a few variables in a YAML config file.
Cool!!
However, when I try and save them, I get an error in RUBY:
undefined method `[]=' for false:FalseClass (NoMethodError)
My function should (In my head at least) be:
But, I'm getting the error above.
I'm new to Ruby (PHP bloke here), tell me where I'm being stupid please :)
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
Upvotes: 1
Views: 3253
Reputation: 106792
The problem is that you created an empty file. And the YAML parser returns false
for an empty string:
YAML.load('') #=> false
Just set config_file
to an empty hash when the YAML loader returned false
:
config_file = YAML.load_file(path_to_file) || {}
Upvotes: 4