Skip to content

Instantly share code, notes, and snippets.

@mmalchuk
Created October 29, 2015 16:45
Show Gist options
  • Save mmalchuk/e9317aada9f0b8d95c0e to your computer and use it in GitHub Desktop.
Save mmalchuk/e9317aada9f0b8d95c0e to your computer and use it in GitHub Desktop.
require 'psych'
module SafeYAML
def self.dump obj, io = nil, options = {}
visitor = Psych::Visitors::YAMLTree.new(options)
visitor << obj
ast = visitor.tree
ast.grep(Psych::Nodes::Scalar).each do |node|
node.style = Psych::Nodes::Scalar::DOUBLE_QUOTED if
node.value =~ /^0[xbod]+/i && node.plain && node.quoted
end
begin
ast.yaml
rescue
# The `yaml` method was introduced in later versions, so fall back to
# constructing a visitor
Psych::Visitors::Emitter.new(io, options).accept ast
end
end
end
puts SafeYAML::dump(hash)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment