-
-
Save thbar/9770758 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
# Attempt at porting https://gist.github.com/nelhage/4507129 to ruby 2.0 | |
# | |
# I just removed all traces of Syck | |
def self.make_yaml_safe! | |
if defined?(Psych) | |
Psych.const_set("UnsafeYAML", Class.new(StandardError)) | |
Psych.module_eval do | |
def self.load(yaml, *args) | |
result = parse(yaml, *args) | |
check_safety(result) | |
result ? result.to_ruby : result | |
end | |
private | |
def self.check_safety(o) | |
check_node(o) | |
case o | |
when Psych::Nodes::Scalar | |
when Psych::Nodes::Sequence | |
o.children.each {|child| check_safety(child)} | |
when Psych::Nodes::Mapping | |
o.children.each {|child| check_safety(child)} | |
when Psych::Nodes::Document | |
check_safety(o.root) | |
when Psych::Nodes::Stream | |
o.children.each {|child| check_safety(child)} | |
when Psych::Nodes::Alias | |
else | |
raise Psych::UnsafeYAML.new("Found unknown node type: #{o.class}") | |
end | |
end | |
def self.check_node(n) | |
# Note thbar: we're allowing HashWithIndifferentAccess here | |
# to cope with https://www.pivotaltracker.com/s/projects/971396 | |
unless n.tag.nil? || ['!ruby/sym', '!ruby/symbol', '!map:HashWithIndifferentAccess', '!map:ActiveSupport::HashWithIndifferentAccess', '!ruby/hash:ActiveSupport::HashWithIndifferentAccess', '!binary', '!'].include?(n.tag) | |
raise Psych::UnsafeYAML.new("Found node with tag: #{n.tag}") | |
end | |
end | |
end | |
end | |
end | |
make_yaml_safe! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment