summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/psych.rb34
1 files changed, 26 insertions, 8 deletions
diff --git a/lib/psych.rb b/lib/psych.rb
index fcbb056..c3292d9 100644
--- a/lib/psych.rb
+++ b/lib/psych.rb
@@ -74,12 +74,15 @@ require 'psych/class_loader'
#
# ==== Reading from a string
#
-# Psych.load("--- a") # => 'a'
-# Psych.load("---\n - a\n - b") # => ['a', 'b']
+# Psych.safe_load("--- a") # => 'a'
+# Psych.safe_load("---\n - a\n - b") # => ['a', 'b']
+# # From a trusted string:
+# Psych.load("--- !ruby/range\nbegin: 0\nend: 42\nexcl: false\n") # => 0..42
#
# ==== Reading from a file
#
-# Psych.load_file("database.yml")
+# Psych.safe_load_file("data.yml", permitted_classes: [Date])
+# Psych.load_file("trusted_database.yml")
#
# ==== Exception handling
#
@@ -548,7 +551,7 @@ module Psych
# end
# list # => ['foo', 'bar']
#
- def self.load_stream yaml, legacy_filename = NOT_GIVEN, filename: nil, fallback: []
+ def self.load_stream yaml, legacy_filename = NOT_GIVEN, filename: nil, fallback: [], **kwargs
if legacy_filename != NOT_GIVEN
warn_with_uplevel 'Passing filename with the 2nd argument of Psych.load_stream is deprecated. Use keyword argument like Psych.load_stream(yaml, filename: ...) instead.', uplevel: 1 if $VERBOSE
filename = legacy_filename
@@ -556,10 +559,10 @@ module Psych
result = if block_given?
parse_stream(yaml, filename: filename) do |node|
- yield node.to_ruby
+ yield node.to_ruby(**kwargs)
end
else
- parse_stream(yaml, filename: filename).children.map(&:to_ruby)
+ parse_stream(yaml, filename: filename).children.map { |node| node.to_ruby(**kwargs) }
end
return fallback if result.is_a?(Array) && result.empty?
@@ -570,9 +573,24 @@ module Psych
# Load the document contained in +filename+. Returns the yaml contained in
# +filename+ as a Ruby object, or if the file is empty, it returns
# the specified +fallback+ return value, which defaults to +false+.
- def self.load_file filename, fallback: false
+ #
+ # NOTE: This method *should not* be used to parse untrusted documents, such as
+ # YAML documents that are supplied via user input. Instead, please use the
+ # safe_load_file method.
+ def self.load_file filename, **kwargs
+ File.open(filename, 'r:bom|utf-8') { |f|
+ self.load f, filename: filename, **kwargs
+ }
+ end
+
+ ###
+ # Safely loads the document contained in +filename+. Returns the yaml contained in
+ # +filename+ as a Ruby object, or if the file is empty, it returns
+ # the specified +fallback+ return value, which defaults to +false+.
+ # See safe_load for options.
+ def self.safe_load_file filename, **kwargs
File.open(filename, 'r:bom|utf-8') { |f|
- self.load f, filename: filename, fallback: fallback
+ self.safe_load f, filename: filename, **kwargs
}
end