ruby-on-rails - 将 ruby​​ 哈希转换为 yaml 时缩进不正确

标签 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"=>{"名称"=>"","密码"=>""}},"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/

相关文章:

ruby-on-rails - 没有路由匹配 [POST] "/login/log_in"

ruby-on-rails - Rails DELETE http 方法呈现页面

ruby-on-rails - 使用 nginx 运行 capybara

azure - Terraform Plan 在 Windows 上为列表变量传递值

ruby-on-rails - 如何在 rails (4.1.5) 中创建装置(对于设计用户)作为 yml.erb?

css - 404 Error Document not found - CSS 样式表未加载到本地主机上具有绝对文件路径的 erb 文件中

ruby-on-rails - 如何 DRY 我在 5 个模型中编写的 has_attached_file

amazon-web-services - 如何在 AWS SAM Cloud-Formation 中使用 Route53 设置自定义域名

linux - 在 YAML 文件中的特定字符串之后传递变量值

css - 格式化只影响显示 block 的右侧