Adding comment to YAML programmatically

2019-02-25 15:44发布

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'

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

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).

1条回答
太酷不给撩
2楼-- · 2019-02-25 16:15
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

more programmatically:

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
查看更多
登录 后发表回答