简体   繁体   中英

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

Am trying to remove the leading : from my YAML output. Here is the code and what I have done below:

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

The Output:

产量

To remove the YAML Separator --- and the Leading : in the keys from my output, here is what I have done:

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

..but the .sub(":", '') part removed only the : of the first leading : .

How do I remove the leading : from my YAML output? Any help is appreciated? Here is what I want below:

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

You need to have keys as strings to skip : generation

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"

You can convert hash keys to strings before generating YAML. The code below goes through a hash recursively convering every key to hash and stringifying every value if it's a hash (note that it's not prepared for circular dependencies in hash).

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

EDIT: Regarding the --- at the beginning, see this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM