2013-01-04 41 views
3

to_yaml方法会生成很好的YAML输出,但我想在某些元素之前包含注释行。有没有办法做到这一点?可以使用Ruby的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 

对我的好处是没有重复(例如,“客户:”只指定一次),数据和评论在一起,来源可作为YAML输出,并且数据结构(在conf中可用)可供使用。

+0

你尝试过什么?是什么让你觉得它不起作用? http://yaml.org/spec/current.html#id2509980 –

+0

增加了额外的细节。 – sutch

回答

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 
+0

这可行,但我不喜欢这是如何分离评论和数据。我用我正在使用的东西更新了我的问题。 – sutch

2

事情是这样的:

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

当然,你将需要步行输入散列自己,要么add()emit()需要。 你可以看看to_yaml方法的来源以便快速入门。

+0

这并不真正评论一个领域,中期哈希,就像他似乎想要的,但。 –

+0

这是一个帮助他开始的例子。让我在答案中澄清一下。 – Zabba

+1

备注:在你的代码中,我得到一个错误'psych/streaming.rb:6:'初始化':错误的参数数量(0代表1)'。为了处理你的代码,我必须用'YAML :: ENGINE.yamler ='syck''来更改YAML引擎(我使用win7中的“ruby 1.9.3p194(2012-04-20)[i386-mingw32]”) 。 – knut

相关问题