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

查看:21
本文介绍了以编程方式向 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

编辑

更以编程方式:

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天全站免登陆