Beertastic
Beertastic

Reputation: 711

Ruby, writing to a YAML file, with arrays

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:

  1. Does the config file exist, if not, just create a blank one.
  2. Now that we know it exists, YAML.open it
  3. set the new/overwriting key/value pairs
  4. re Write the file

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

Answers (1)

spickermann
spickermann

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

Related Questions