diff options
author | Aaron Patterson <aaron.patterson@gmail.com> | 2016-06-24 16:37:50 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2016-06-24 16:37:50 +0800 |
commit | c364faf80707f963a5f7e11b364563b5934fb265 (patch) | |
tree | 209e3f77b0c8123ff7842dea5ee8ad72aeb9cd5f | |
parent | 7b1201209a658e6e45aa3fc85b56dc8f61aa4fb1 (diff) | |
parent | cbef14d4f18a56cbc9e1c7d9bcdbcf5dc6510a68 (diff) | |
download | psych-c364faf80707f963a5f7e11b364563b5934fb265.zip |
Merge pull request #264 from tuexss/load_file-default
Add optional fallback return value parameter
-rw-r--r-- | lib/psych.rb | 19 | ||||
-rw-r--r-- | test/psych/test_psych.rb | 5 |
2 files changed, 17 insertions, 7 deletions
diff --git a/lib/psych.rb b/lib/psych.rb index f442e54..b2a690b 100644 --- a/lib/psych.rb +++ b/lib/psych.rb @@ -229,6 +229,8 @@ module Psych # The version of libyaml Psych is using LIBYAML_VERSION = Psych.libyaml_version.join '.' + FALLBACK = Struct.new :to_ruby # :nodoc: + ### # Load +yaml+ in to a Ruby data structure. If multiple documents are # provided, the object contained in the first document will be returned. @@ -248,8 +250,8 @@ module Psych # ex.file # => 'file.txt' # ex.message # => "(file.txt): found character that cannot start any token" # end - def self.load yaml, filename = nil - result = parse(yaml, filename) + def self.load yaml, filename = nil, fallback = false + result = parse(yaml, filename, fallback) result ? result.to_ruby : result end @@ -321,11 +323,11 @@ module Psych # end # # See Psych::Nodes for more information about YAML AST. - def self.parse yaml, filename = nil + def self.parse yaml, filename = nil, fallback = false parse_stream(yaml, filename) do |node| return node end - false + fallback end ### @@ -466,9 +468,12 @@ module Psych ### # Load the document contained in +filename+. Returns the yaml contained in - # +filename+ as a Ruby object - def self.load_file filename - File.open(filename, 'r:bom|utf-8') { |f| self.load f, filename } + # +filename+ as a Ruby object, or if the file is empty, it returns + # the specified default return value, which defaults to an empty Hash + def self.load_file filename, fallback = false + File.open(filename, 'r:bom|utf-8') { |f| + self.load f, filename, FALLBACK.new(fallback) + } end # :stopdoc: diff --git a/test/psych/test_psych.rb b/test/psych/test_psych.rb index 7de9e07..508519b 100644 --- a/test/psych/test_psych.rb +++ b/test/psych/test_psych.rb @@ -144,6 +144,11 @@ class TestPsych < Psych::TestCase } end + def test_load_file_with_fallback + t = Tempfile.create(['empty', 'yml']) + assert_equal Hash.new, Psych.load_file(t.path, Hash.new) + end + def test_parse_file Tempfile.create(['yikes', 'yml']) {|t| t.binmode |