我正在尝试使用 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"=>{"名称"=>"","密码"=>""}},"nexus"=>{"basic"=>{"名称"=>"cpreader","密码"=>"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
如何从转储中获得预期的输出?
最佳答案
我认为您在这里做的最简单的事情就是将凭据 key 也放入哈希中,即更改您的模板片段,使其成为一行:
<%= get_yaml( context ) %>
并将您的 get_yaml 方法更改为:
def get_yaml(obj)
YAML.dump({'credentials' => obj['imports']['external_repositories']['credentials']})
.sub(/.*?\n/,'')
end
如果这对您不起作用,例如,如果您没有提到的凭据 key 下面还有其他 key ,您也可以执行以下操作:
def get_yaml(obj)
YAML.dump(obj['imports']['external_repositories']['credentials'])
.sub(/^---\n/,'')
.gsub(/\n/m,"\n ")
end
其中 gsub(/\n/m,"\n ")
将所有换行符替换为换行符加两个空格。
关于ruby-on-rails - 将 ruby 哈希转换为 yaml 时缩进不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53663773/