Created
October 29, 2015 16:45
-
-
Save mmalchuk/e9317aada9f0b8d95c0e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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