可以使用Ruby的YAML模块嵌入注释吗? [英] Can Ruby's YAML module be used to embed comments?

查看:93
本文介绍了可以使用Ruby的YAML模块嵌入注释吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

to_yaml方法产生不错的YAML输出,但是我想在某些元素之前添加注释行.有办法吗?

The to_yaml method produces nice YAML output, but I would like to include comment lines before some of the elements. Is there a way to do so?

例如,我想制作:

# 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模块是否有办法实现.

... but am not sure if the YAML module even has a way to accomplish.

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

UPDATE: I ended up not using the solution which used regexes to insert the comments, since it required the separation of the data from the comments. The easiest and most understandable solution for me is:

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中可用)可供使用.

The benefit to me is that nothing is repeated (for example, 'client:' is only specified once), the data and comments are together, the source can be outputted as YAML, and the data structure (available in conf) is available for use.

推荐答案

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

You can do a string replace on all the insertions:

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

这篇关于可以使用Ruby的YAML模块嵌入注释吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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