ruby - Ruby 的 YAML 模块可以用来嵌入评论吗?

标签 ruby yaml to-yaml

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

最佳答案

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

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 - Ruby 的 YAML 模块可以用来嵌入评论吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14149570/

相关文章:

ruby-on-rails - 为什么 foreign_key 被忽略了?

sql - rails/SQL : finding invoices by checking two sums

python - 在 Python 中漂亮地将 2D 数组转储到 YAML

json - 如何在没有数组的情况下拥有多个无限对象 - Open API/Swagger

ruby - ruby 中的深度限制 pp 或 to_yaml

ruby-on-rails - 如何在 Rails 中使用 to_yaml 方法,并删除 '---'

javascript - jQuery 中的条件语句

python - 使用 Python 删除 YAML 文件中的 block

ruby-on-rails - rails : How to Implement Number of Post Views?