一个YAML对象可以引用另一个吗?

Joh*_*hir 5 ruby yaml

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

intro: "Hello, dear user."

registration: $intro Thanks for registering!

new_message: $intro You have a new message!
Run Code Online (Sandbox Code Playgroud)

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

我正在使用标准的ruby yaml解析器.

这可能吗?

ram*_*ion 7

一些yaml对象确实引用其他对象:

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
Run Code Online (Sandbox Code Playgroud)

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

YAML不支持字符串插值 - 这是你似乎想要做的 - 但是没有理由你不能更详细地编码它:

intro: Hello, dear user
registration: 
- "%s Thanks for registering!"
- intro
new_message: 
- "%s You have a new message!"
- intro
Run Code Online (Sandbox Code Playgroud)

然后你可以在加载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
Run Code Online (Sandbox Code Playgroud)

这将产生以下因素interpolated:

{
  "intro"=>"Hello, dear user", 
  "registration"=>"Hello, dear user Thanks for registering!", 
  "new_message"=>"Hello, dear user You have a new message!"
}
Run Code Online (Sandbox Code Playgroud)