I have a small script to automate some things in YAML files.
I read the original YAML file and convert it into a hash and then dump it to the file after modifying it:
File.open(output_file, "w") do |out|
YAML.dump(modified_hash, out)
end
That works fine, but it removes double-quotes around the string if they aren't needed. That's valid YAML, but it doesn't look very nice.
I could add a space at the end of every string to force single-quotes, but I'm not too happy with that. Is there any way of forcing double-quotes around strings?
This works pretty well. I got it from here
require 'psych'
ast = Psych.parse_stream DATA.read
# First pass, quote everything
ast.grep(Psych::Nodes::Scalar).each do |node|
node.plain = false
node.quoted = true
node.style = Psych::Nodes::Scalar::DOUBLE_QUOTED
end
# Second pass, unquote keys
ast.grep(Psych::Nodes::Mapping).each do |node|
node.children.each_slice(2) do |k, _|
k.plain = true
k.quoted = false
k.style = Psych::Nodes::Scalar::ANY
end
end
puts ast.yaml
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With