Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

YAML.load_file returns false for empty files #149

Open
robinboening opened this Issue · 2 comments

3 participants

@robinboening

When loading an empty yml file with YAML.load_file it returns false.
This behavior feels a bit strange to me and I would expect to get an empty Hash instead.

I often notice myself writing code like this and adding a comment to remember why I did this:

YAML.load_file(file) || {} if File.exists?(file) # YAML.load_file returns false if file is empty.

Is there a certain reason for returning false?
How big would be the impact when changing its behavior?

cheers!
Robin

@tenderlove
Owner

Hi! Honestly, I think it would make more sense for it to return nil rather than false (given that a YAML document like --- represents nil), but false is what Syck returned. Why would you think a hash?

We could change the return value, but it would have to be a major version.

@parkr

Ran into this strange behaviour this morning. I'd love to have nil instead of false (as it makes more sense), but my ideal solution would be to have some sort of fallback option:

YAML.load_file(File.join("i-am", "empty.yml"), Hash.new).fetch(my_key)

If the file is there but empty, we presently get a NoMethodError on FalseClass, which makes me :crying_cat_face:. With some sort of fallback solution (à la Hash#fetch), one could get a desired default value back instead of nil or false.

What do you think?

@joshcooper joshcooper referenced this issue from a commit in joshcooper/puppet
@joshcooper joshcooper (#23369) Allow caller to override YAML.load_file returning false
According to tenderlove/psych#149, Syck and
Psych return false when ::YAML.load_file tries to parse an empty file.

Since Puppet::Indirector::Yaml#find calls Puppet::Util::Yaml.load_file
directly, we can't change the semantics of what it returns.

Instead we allow the caller to explicitly specify what the default value
should be.
4205a8c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.