将ruby哈希转换为yaml时缩进不当

时间:2018-12-07 05:30:23

标签: ruby-on-rails yaml erb

我试图使用YAML.dump(obj)将ruby哈希对象转换为YAML格式,但是即使使用转储选项后,缩进也不正确。

我下面有可执行的ruby脚本:

#!/usr/bin/ruby

require "yaml"
require "erb"

context_path = ARGV[0]
context = YAML.load_file(context_path)['context']

def get_yaml(obj)
  YAML.dump( obj['imports']['external_repositories']['credentials'] ).sub(/.*?\n/,'')
end

-obj['imports']['external_repositories']['credentials']的值是

{"iacbox"=>{"basic"=>{"name"=>"", "password"=>""}}, "nexus"=>{"basic"=>{"name"=>"cpreader", "password"=>"swordfish"}}}

注意:我使用sub方法在输出的开头删除了“-”。

ERB模板将上述get_yaml方法调用为:

credentials:
   <%= get_yaml( context ) %>

即将出现的输出是:

credentials:
iacbox:
  basic:
    name: ''
    password: ''
nexus:
  basic:
    name: cpreader
    password: swordfish

当我期望输出为:

credentials:
  iacbox:
    basic:
      name: ''
      password: ''
  nexus:
    basic:
      name: cpreader
      password: swordfish

如何从转储中获得预期的输出?

1 个答案:

答案 0 :(得分:0)

我认为您在这里要做的最简单的事情就是将凭据密钥也放入哈希中,即更改模板代码段,使其仅一行:

<%= get_yaml( context ) %>

并将您的get_yaml方法更改为:

def get_yaml(obj)
  YAML.dump({'credentials' => obj['imports']['external_repositories']['credentials']})
    .sub(/.*?\n/,'')
end

如果这对您不起作用,例如,如果您在未提及的凭据密钥下还有其他密钥,则还可以执行以下操作:

def get_yaml(obj)
  YAML.dump(obj['imports']['external_repositories']['credentials'])
    .sub(/^---\n/,'')
    .gsub(/\n/m,"\n  ")
end

gsub(/\n/m,"\n ")用换行符加上两个空格替换所有换行符。