5

to_yaml 方法产生了不错的 YAML 输出,但我想在某些元素之前包含注释行。有没有办法这样做?

例如,我想制作:

# hostname or IP address of client
client: host4.example.com
# hostname or IP address of server
server: 192.168.222.222

从类似的东西:

{
  :client => 'host4.example.com',
  :server => '192.168.222.222',
}.to_yaml

...但不确定 YAML 模块是否有办法完成。

更新:我最终没有使用使用正则表达式插入评论的解决方案,因为它需要将数据与评论分开。对我来说最简单和最容易理解的解决方案是:

require 'yaml'

source = <<SOURCE
# hostname or IP address of client
client: host4.example.com
# hostname or IP address of server
server: 192.168.222.222
SOURCE

conf = YAML::load(source)

puts source

对我的好处是没有任何重复(例如'client:'只指定一次),数据和注释在一起,源可以输出为YAML,数据结构(conf中可用)可用于利用。

4

3 回答 3

3

您可以对所有插入进行字符串替换:

require 'yaml'

source = {
  :client => 'host4.example.com',
  :server => '192.168.222.222',
}.to_yaml

substitution_list = {
  /:client:/ => "# hostname or IP address of client\n:client:",
  /:server:/ => "# hostname or IP address of server\n:server:"
}

substitution_list.each do |pattern, replacement|
  source.gsub!(pattern, replacement)
end

puts source

输出:

--- 
# hostname or IP address of client
:client: host4.example.com
# hostname or IP address of server
:server: 192.168.222.222
于 2013-01-04T01:19:43.850 回答
2

像这样的东西:

my_hash = {a: 444}
y=YAML::Stream.new()
y.add(my_hash)
y.emit("# this is a comment")

当然,您需要自己add()emit()根据需要遍历输入哈希。您可以查看该to_yaml方法的来源以快速入门。

于 2013-01-04T01:02:07.033 回答
1

这并不完美(例如,没有中间阵列支持),但它可以满足我的需求。

  def commentify_yaml(db)
    ret = []
    db.to_yaml(line_width: -1).each_line do |l|
      if l.match(/^\s*:c\d+:/)
        l = l.sub(/:c(\d+)?:/, '#').
            sub(/(^\s*# )["']/, '\1').
            sub(/["']\s*$/, '').
            gsub(/''(\S+?)''/, "'\\1'").
            gsub(/(\S)''/, "\\1'")
      end
      ret << l.chomp
    end
    ret * "\n"
  end

示例用法。

commentify_yaml(
  {
    c1: 'Comment line 1',
    c2: 'Comment line 2',
    'hash_1' => {
      c1: 'Foo',
      c2: 'Bar',
      'key_1' => "Hello!",
    },
    'baz' => qux,
    c3: 'Keep up-numbering the comments in the same hash',
    'array_1' => [
       1,
       2,
       3
     ]
  }
)

==>

# Comment line 1
# Comment line 2
hash_1:
  # Foo
  # Bar
  key_1: "Hello!"
baz: "Value of qux"
# Keep up-numbering the comments in the same hash
array_1:
- 1
- 2
- 3

(注意:Syck 并没有按照他们应该的方式缩进数组。)

于 2019-11-03T20:35:55.083 回答