以编程方式向YAML添加评论 [英] Adding comment to YAML programmatically

查看:125
本文介绍了以编程方式向YAML添加评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出简单的YAML文件进行本地化:

Given the simple YAML file for localisation:

root:
  label: 'Test'
  account: 'Account'
  add: 'Add'
  local_folder: 'Local folder'
  remote_folder: 'Remote folder'
  status: 'Status'
    subkey: 'Some value'

如何在Ruby中以编程方式在某些行的末尾添加注释? 我需要得到类似的东西:

How can I add a comment to the end of line for some key programmatically in Ruby? I need to get something like:

root:
  label: 'Test'
  account: 'Account'
  add: 'Add'
  local_folder: 'Local folder' #Test comment
  remote_folder: 'Remote folder'
  status: 'Status'
    subkey: 'Some value' #Test comment

是否还有其他方法(可能使用Linux sed)来完成此任务? 我的原因是准备要进一步处理的YAML文件. (注释将用作外部工具标识密钥的标签).

Are there any other ways (may be using Linux sed) to accomplish this? My reason is to prepare the YAML file for further processing. (comments will act as labels for external tool to identify keys).

推荐答案

require 'yaml'

str = <<-eol
root:
  label: 'Test'
  account: 'Account'
  add: 'Add'
  local_folder: 'Local folder'
  remote_folder: 'Remote folder'
  status: 'Status'
  subkey: 'Some value'
eol

h = YAML.load(str)
h["root"]["local_folder"] = h["root"]["local_folder"] + " !Test comment"
h["root"]["subkey"] = h["root"]["subkey"] + " !Test comment"

puts h.to_yaml 

# >> ---
# >> root:
# >>   label: Test
# >>   account: Account
# >>   add: Add
# >>   local_folder: Local folder !Test comment
# >>   remote_folder: Remote folder
# >>   status: Status
# >>   subkey: Some value !Test comment

EDIT

EDIT

更多以编程方式:

require 'yaml'

str = <<-eol
root:
  label: 'Test'
  account: 'Account'
  add: 'Add'
  local_folder: 'Local folder'
  remote_folder: 'Remote folder'
  status: 'Status'
  subkey: 'Some value'
eol

h = YAML.load(str)
%w(local_folder subkey).each {|i| h["root"][i] = h["root"][i] + " !Test comment" }

puts h.to_yaml 

# >> ---
# >> root:
# >>   label: Test
# >>   account: Account
# >>   add: Add
# >>   local_folder: Local folder !Test comment
# >>   remote_folder: Remote folder
# >>   status: Status
# >>   subkey: Some value !Test comment

这篇关于以编程方式向YAML添加评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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