Skip to content

Instantly share code, notes, and snippets.

@we4tech
Created November 4, 2019 19:29

Revisions

  1. we4tech created this gist Nov 4, 2019.
    31 changes: 31 additions & 0 deletions yaml_preserved_string_quote.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    class YAMLPreservedStringQuote
    def initialize(*doublequoted_nodes)
    @doublequoted_nodes = doublequoted_nodes
    end

    def load(str)
    ast = YAML.parse_stream(StringIO.new(str))

    ast.grep(Psych::Nodes::Mapping).each do |node|
    node.children.each_slice(2) do |key, value|
    next unless @doublequoted_nodes.include?(key.value)

    if value.is_a?(Psych::Nodes::Sequence)
    value.children.each(&method(:double_quote!))
    else
    double_quote!(value)
    end
    end
    end

    ast
    end

    private

    def double_quote!(node)
    node.plain = false
    node.quoted = true
    node.style = Psych::Nodes::Scalar::DOUBLE_QUOTED
    end
    end