如何将符号转换为字符串(即带前导:) ruby to_yaml

How to convert symbols to strings (i.e. strip leading :) ruby to_yaml

我正在尝试从我的 YAML 输出中删除前导 :。这是代码和我在下面所做的:

model/attribution_channel.rb

DEFAULT_BONUS_CONFIG =  {
  sign_up: {
    currency: 'ngn',
    type: 'flat',
    amount: 1000
  },
  visit: {
    currency: 'ngn',
    type: 'flat',
    amount: 5
  }
}

view/form.slim.html

AttributionChannel::DEFAULT_BONUS_CONFIG.to_yaml

输出:

从我的输出中删除 YAML 分隔符 ---Leading : 在键 中,这是我所做的:

AttributionChannel::DEFAULT_BONUS_CONFIG.to_yaml.gsub("---\n", '').sub(":", '')

..但是 .sub(":", '') 部分仅删除了第一个前导 ::

如何从我的 YAML 输出中删除前导 :?任何帮助表示赞赏?下面是我想要的:

sign_up:
  currency: ngn
  type: flat
  amount: 1000
visit:
  currency: ngn
  type: flat
  amount: 5

您可以在生成 YAML 之前将散列键转换为字符串。下面的代码递归地遍历一个散列,将每个键转换为散列,如果它是一个散列,则对每个值进行字符串化(请注意,它没有为散列中的循环依赖做好准备)。

def stringify(hash)
  hash.map{|k, v| [k.to_s, v.is_a?(Hash) ? stringify(v) : v] }.to_h
end  

puts stringify(DEFAULT_BONUS_CONFIG).to_yaml

---
sign_up:
  currency: ngn
  type: flat
  amount: 1000
visit:
  currency: ngn
  type: flat
  amount: 5

编辑:关于开头的 ---,参见 this answer

您需要将键作为字符串才能跳过 : 生成

require 'active_support/core_ext/hash/keys'
require 'yaml'

DEFAULT_BONUS_CONFIG.deep_stringify_keys.to_yaml.gsub("---\n", '')

 => "sign_up:\n  currency: ngn\n  type: flat\n  amount: 1000\nvisit:\n  currency: ngn\n  type: flat\n  amount: 5\n"