一个 YAML 对象可以引用另一个对象吗? [英] Can one YAML object refer to another?

查看:59
本文介绍了一个 YAML 对象可以引用另一个对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让一个 yaml 对象引用另一个对象,如下所示:

I'd like to have one yaml object refer to another, like so:

intro: "Hello, dear user."

registration: $intro Thanks for registering!

new_message: $intro You have a new message!

上述语法只是它可能如何工作的一个例子(这也是它在 这个 cpan 模块.)

The above syntax is just an example of how it might work (it's also how it seems to work in this cpan module.)

我使用的是标准的 ruby​​ yaml 解析器.

I'm using the standard ruby yaml parser.

这可能吗?

推荐答案

某些 yaml 对象确实会引用其他对象:

Some yaml objects do refer to the others:

irb> require 'yaml'
#=> true
irb> str = "hello"
#=> "hello"
irb> hash = { :a => str, :b => str }
#=> {:a=>"hello", :b=>"hello"}
irb> puts YAML.dump(hash)
---
:a: hello
:b: hello
#=> nil
irb> puts YAML.dump([str,str])
---
- hello
- hello
#=> nil
irb> puts YAML.dump([hash,hash])
---
- &id001
  :a: hello
  :b: hello
- *id001
#=> nil

请注意,它并不总是重用对象(字符串只是重复),但有时会(哈希定义一次并通过引用重用).

Note that it doesn't always reuse objects (the string is just repeated) but it does sometimes (the hash is defined once and reused by reference).

YAML 不支持字符串插值 - 这就是您似乎正在尝试做的 - 但没有理由您不能对其进行更详细的编码:

YAML doesn't support string interpolation - which is what you seem to be trying to do - but there's no reason you couldn't encode it a bit more verbosely:

intro: Hello, dear user
registration: 
- "%s Thanks for registering!"
- intro
new_message: 
- "%s You have a new message!"
- intro

然后您可以在加载 YAML 后对其进行插值:

Then you can interpolate it after you load the YAML:

strings = YAML::load(yaml_str)
interpolated = {}
strings.each do |key,val|
  if val.kind_of? Array
    fmt, *args = *val
    val = fmt % args.map { |arg| strings[arg] }
  end
  interpolated[key] = val
end

这将为 interpolated 产生以下结果:

And this will yield the following for interpolated:

{
  "intro"=>"Hello, dear user", 
  "registration"=>"Hello, dear user Thanks for registering!", 
  "new_message"=>"Hello, dear user You have a new message!"
}

这篇关于一个 YAML 对象可以引用另一个对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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