Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of --- in yaml

Tags:

ruby

yaml

I came across this yaml document:

--- !ruby/object:MyClass
myint: 100
mystring: hello world

What does the line:

--- !ruby/object:MyClass

mean?

like image 939
Pika Supports Ukraine Avatar asked Oct 31 '18 22:10

Pika Supports Ukraine


2 Answers

In YAML, --- is the end of directives marker.

A YAML document may begin with a number of YAML directives (currently, two directives are defined, %YAML and %TAG). Since a text node (for example) can also start with a % character, there needs to be a way to distinguish between directives and text. This is achieved using the end of directives marker --- which signals the end of the directives and the beginning of the document.

Since directives are allowed to be empty, --- can also serve as a document separator.

YAML also has an end of document marker .... However, this is not often used, because and end of directives marker / document separator also implies the end of the document. You need it if you want to have multiple documents with directives within the same stream or when you want to indicate that a document is finished without necessarily starting a new one (e.g. in cases where there may be significant time passing between the end of one document and the start of another).

Many YAML emitters, and Psych is no exception, always emit an end of directives marker at the beginning of each document. This allows you to easily concatenate multiple documents into a single stream without doing any additional processing of the documents.

The other half of that line, !ruby/object:MyClass, is a tag. A tag is used to give a type to the following node. In YAML, every node has a type, even if it is implicit. You can also write the tag explicitly, for example text nodes have the type (tag) !!str. This can be useful in certain circumstances, for example here:

!!str 2018-10-31

This tells YAML that 2018-10-31 is text, not a date.

!ruby/object:MyClass is a tag used by Psych to indicate that the node is a serialized Ruby Object which is an instance of class MyClass. This way, when deserializing the document, Psych knows what class to instantiate and how to treat the node.

like image 138
Jörg W Mittag Avatar answered Oct 22 '22 07:10

Jörg W Mittag


According to yaml.org, '---' indicates the start of a document.

https://yaml.org/spec/1.2/spec.html for official specifications.

like image 26
john ktejik Avatar answered Oct 22 '22 07:10

john ktejik