Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add optional fallback return value parameter #264

Merged
merged 1 commit into from
Jun 24, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions lib/psych.rb
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,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.
Expand All @@ -247,8 +249,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

Expand Down Expand Up @@ -320,11 +322,11 @@ def self.safe_load yaml, whitelist_classes = [], whitelist_symbols = [], aliases
# 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

###
Expand Down Expand Up @@ -465,9 +467,12 @@ def self.load_stream yaml, filename = nil

###
# 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:
Expand Down
5 changes: 5 additions & 0 deletions test/psych/test_psych.rb
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,11 @@ def test_load_file
}
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
Expand Down