Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emit YAML in Ruby expanding aliases

I am looking for a way to emit YAML files avoiding the use of aliases (mostly for simplified human readability). I think extending Psych::Visitors::Emitter or Psych::Visitors::Visitor is the way to go, but I cannot actually find where Ruby decides whether to dump an anchor in full, or reference it with an alias.

I wouldn't even mind if the anchors were used repeatedly (with their &...... references), I just need to expand aliases to the full structures.

I am aware of similar questions being asked in the past, but:

  • Ruby YAML write without aliases remained unanswered
  • Is it possible to emit valid YAML with anchors / references disabled using Ruby or Python? gave answer for Python but not for Ruby
like image 455
Frigo Avatar asked Jul 01 '14 10:07

Frigo


People also ask

What is aliases in YAML?

YAML Anchors and Alias Anchors and Aliases are YAML constructions that allow you to reduce repeat syntax and extend existing data nodes. You can place Anchors ( & ) on an entity to mark a multi-line section. You can then use an Alias ( * ) call that anchor later in the document to reference that section.

What is a YAML file in Ruby?

Writing configuration files typically involves using the YAML data serialization language. YAML is an abbreviation that is a mark-up language, not a document. It is frequently employed in programs that store or transport data and configuration files. Data serialization is a feature of the YAML module in Ruby.


1 Answers

One simple (hacky) approach I used was convert the yaml to json. and then convert it back to YAML. new YAML does not contain aliases/anchors.

require 'json'

jsonObj = oldYaml.to_json
newYaml = YAML.load(jsonObj)
print newYaml.to_yaml
like image 169
chetan pawar Avatar answered Oct 14 '22 01:10

chetan pawar