以编程方式向YAML添加注释

时间:2013-06-20 15:30:54

标签: ruby parsing yaml

给出用于本地化的简单YAML文件:

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

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

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文件以进行进一步处理。 (注释将作为外部工具的标签来识别密钥)。

1 个答案:

答案 0 :(得分:0)

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
相关问题