Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it a YAML Document? #49

Closed
trans opened this issue Feb 29, 2012 · 5 comments
Closed

Is it a YAML Document? #49

trans opened this issue Feb 29, 2012 · 5 comments

Comments

@trans
Copy link

trans commented Feb 29, 2012

Is there any way to detect if a file and/or string is YAML?

Maybe something like:

YAML.document?(io_or_text)

would be a good addition, if not.

@tenderlove
Copy link
Member

I don't think there's a good way to do that without parsing the entire document. The problem is that documents can be implicitly started. That means the string foo is a valid yaml document:

irb(main):001:0> require 'psych'
=> true
irb(main):002:0> Psych.load 'foo'
=> "foo"
irb(main):003:0>

You would essentially have to parse the entire string to make sure it was YAML. Say the document? method returned true. Would people using Psych parse the document a second time? If so, why not just parse the document once and rescue from an exception?

We wouldn't want to test IO objects because it may not be possible to rewind the IO (possibly a socket or something).

@trans
Copy link
Author

trans commented Mar 2, 2012

Good points.

Technically I believe the YAML spec requires a document start with ---. I was simply thinking of a method that checks the first non-comment/non-blank line for this marker. The method's documentation could explain it's limitations with implicit documents. In fact, the method could be called something like YAML.explicit_document?(string) to help clarify that.

Anyhow, obviously not the most pressing feature. Just a convenience that I could have made use of a few times, so I thought I'd suggest it.

@tenderlove
Copy link
Member

Gotcha! :-)

Unfortunately, the 1.1 spec says that YAML documents are not required to start with ---. Look at the second production here. The l-implicit-document production does not require a ---, where an explicit document does require it.

@trans
Copy link
Author

trans commented Mar 2, 2012

You're using 1.1, not 1.2?

@tenderlove
Copy link
Member

libyaml only supports 1.1 at this point, so ya, psych is only working with the 1.1 spec. Once libyaml gets an upgrade, we will too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants