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

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

问题描述

我正在使用 Jammit 为 Rails 应用程序打包资产,我有一些资产文件喜欢被包括在几个组中的每一个.例如,我希望 Sammy 及其插件同时出现在我的 mobile 中screen JS 包.

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.

我已经试过了:

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

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

还有这个:

mobile:
  - *SAMMY

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

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:我意识到在这种情况下 SAMMY 数组中只有两个元素,所以给每个元素一个别名和引用也不会太糟糕都在每个包中.对于这种情况,这很好,但是当有五个或十个具有特定加载顺序的元素时,很快就会变得无法维护.

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.

推荐答案

您的示例是有效的 YAML(一个方便的检查位置是 YPaste),但它没有定义合并的作用.根据规范,合并键可以有一个值:

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. 一个映射,在这种情况下它被合并到父映射中.
  2. 一系列映射,在这种情况下,每个映射都被一个一个地合并到父映射中.

无法在 YAML 级别合并序列.

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

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! }

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

(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天全站免登陆