Is there a way to alias/anchor an array in YAML?

谁说胖子不能爱 提交于 2019-11-28 20:07:36
Jesse Beder

Your example is valid YAML (a convenient place to check is YPaste), but it's not defined what the merge does. Per the spec, a merge key can have a value:

  1. A mapping, in which case it's merged into the parent mapping.
  2. A sequence of mappings, in which case each is merged, one-by-one, into the parent mapping.

There's no way of merging sequences on YAML level.

You can, however, do this in code. Using the YAML from your second idea:

mobile:
  - *SAMMY

you'll get nested sequences - so flatten them! Assuming you have a mapping of such nested sequences:

data = YAML::load(File.open('test.yaml'))
data.each_pair { |key, value| value.flatten! }

(Of course, if you have a more complicated YAML file, and you don't want every sequence flattened (or they're not all sequences), you'll have to do some filtering.)

Closest solution I know of is this one:

sammy:
  - &SAMMY1
    public/javascripts/vendor/sammy.js
  - &SAMMY2
    public/javascripts/vendor/sammy*.js

mobile:
  - *SAMMY1
  - *SAMMY2
  - public/javascripts/something_else.js

Alternatively, as already suggested, flatten the nested lists in a code snippet.

Note: according to yaml-online-parser, your first suggestion is not a valid use of << (used to merge keys from two dictionaries. The anchor then has to point to another dictionary I believe.

If you want mobile to be equal to sammy, you can just do:

mobile: *SAMMY

However if you want mobile to contain other elements in addition to those in sammy, there's no way to do that in YAML to the best of my knowledge.

As it has been suggested, when you need to flatten a list, at least in ruby, it is trivial to add a "!flatten" type specifier to mobile and implement a class that extends Array, adds the yaml_tag and flattens the coder seq on init_with.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!