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

ε祈祈猫儿з 提交于 2019-11-30 06:28:54

问题


I'm using Jammit to package assets up for a Rails application and I have a few asset files that I'd like to be included in each of a few groups. For example, I'd like Sammy and its plugins to be in both my mobile and screen JS packages.

I've tried this:

sammy: &SAMMY
  - public/javascripts/vendor/sammy.js
  - public/javascripts/vendor/sammy*.js

mobile:
  <<: *SAMMY
  - public/javascripts/something_else.js

and this:

mobile:
  - *SAMMY

but both put the Sammy JS files in a nested Array, which Jammit can't understand. Is there a syntax for including the elements of an Array directly in another Array?

NB: I realize that in this case there are only two elements in the SAMMY Array, so it wouldn't be too bad to give each an alias and reference both in each package. That's fine for this case, but quickly gets unmaintainable when there are five or ten elements that have a specific load order.


回答1:


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.)




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/4948933/is-there-a-way-to-alias-anchor-an-array-in-yaml

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