有没有办法在YAML中对数组进行别名/锚定? [英] Is there a way to alias/anchor an array in YAML?

查看:87
本文介绍了有没有办法在YAML中对数组进行别名/锚定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jammit 将资产打包为Rails应用程序,并且我有一些资产文件喜欢被包括在几个小组中的每个小组中.例如,我希望 Sammy 及其插件同时位于我的mobilescreen JS软件包中.

我已经尝试过了:

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

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

和这个:

mobile:
  - *SAMMY

,但都将Sammy JS文件放在嵌套数组中,Jammit无法理解.是否存在将数组元素直接包含在另一个数组中的语法?

NB :我意识到在这种情况下,在SAMMY数组中只有两个元素,因此在每个包中给每个别名和两个引用都不错.在这种情况下很好,但是当有五个或十个具有特定加载顺序的元素时,很快就变得难以维护.

解决方案

您的示例是有效的YAML(方便检查的地方是规范,合并键可以具有一个值:

  1. 映射,在这种情况下,它会合并到父映射中.
  2. 一系列映射,在这种情况下,每个映射都被一对一合并到父映射中.

无法在YAML级别上合并序列.

但是,您可以在代码中执行此操作.从第二个想法开始使用YAML:

mobile:
  - *SAMMY

您将获得嵌套序列-将其展平!假设您具有此类嵌套序列的映射:

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

(当然,如果您有一个更复杂的YAML文件,并且您不想平整每个序列(或者它们不是全部序列),则必须进行一些过滤.)

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.

解决方案

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

这篇关于有没有办法在YAML中对数组进行别名/锚定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆