diff options
author | Aaron Patterson <tenderlove@ruby-lang.org> | 2020-11-18 15:49:58 -0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-11-18 15:49:58 -0800 |
commit | a04a906feac6e5fdfb7c786f3efbdf9ecd339e82 (patch) | |
tree | 23b545e39d29ae7740f2f625a3a8ef3d2e375304 /lib | |
parent | 67ecafb0e2aed5974adff45280080eab1e25656d (diff) | |
parent | 0210e310d04cbc9b236ccdde6caaf79aab4eb794 (diff) | |
download | psych-a04a906feac6e5fdfb7c786f3efbdf9ecd339e82.zip |
Merge pull request #469 from marcandre/safety_first
Add `Psych.safe_load_file`. Tweak doc to provide `safe_` examples.
Diffstat (limited to 'lib')
-rw-r--r-- | lib/psych.rb | 24 |
1 files changed, 21 insertions, 3 deletions
diff --git a/lib/psych.rb b/lib/psych.rb index b09866a..a5de756 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 # @@ -571,12 +574,27 @@ 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+. + # + # 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.safe_load f, filename: filename, **kwargs + } + end + # :stopdoc: @domain_types = {} def self.add_domain_type domain, type_tag, &block |