aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--ext/psych/lib/psych.rb9
-rw-r--r--ext/psych/lib/psych/nodes/node.rb10
-rw-r--r--test/psych/test_psych.rb19
3 files changed, 32 insertions, 6 deletions
diff --git a/ext/psych/lib/psych.rb b/ext/psych/lib/psych.rb
index 59307e3d99..9b4b215b67 100644
--- a/ext/psych/lib/psych.rb
+++ b/ext/psych/lib/psych.rb
@@ -153,10 +153,15 @@ module Psych
# Example:
#
# Psych.dump(['a', 'b']) # => "---\n- a\n- b\n"
- def self.dump o, options = {}
+ def self.dump o, io = nil, options = {}
+ if Hash === io
+ options = io
+ io = nil
+ end
+
visitor = Psych::Visitors::YAMLTree.new options
visitor << o
- visitor.tree.to_yaml
+ visitor.tree.to_yaml io
end
###
diff --git a/ext/psych/lib/psych/nodes/node.rb b/ext/psych/lib/psych/nodes/node.rb
index 0de768c7ac..3ab9acae43 100644
--- a/ext/psych/lib/psych/nodes/node.rb
+++ b/ext/psych/lib/psych/nodes/node.rb
@@ -30,10 +30,12 @@ module Psych
# Convert this node to YAML.
#
# See also Psych::Visitors::Emitter
- def to_yaml
- io = StringIO.new
- Visitors::Emitter.new(io).accept self
- io.string
+ def to_yaml io = nil
+ real_io = io || StringIO.new
+
+ Visitors::Emitter.new(real_io).accept self
+ return real_io.string unless io
+ io
end
end
end
diff --git a/test/psych/test_psych.rb b/test/psych/test_psych.rb
index 88fe83c19a..22baa1489e 100644
--- a/test/psych/test_psych.rb
+++ b/test/psych/test_psych.rb
@@ -1,5 +1,8 @@
require_relative 'helper'
+require 'stringio'
+require 'tempfile'
+
class TestPsych < Psych::TestCase
def test_dump_stream
things = [22, "foo \n", {}]
@@ -7,6 +10,22 @@ class TestPsych < Psych::TestCase
assert_equal things, Psych.load_stream(stream)
end
+ def test_dump_file
+ hash = {'hello' => 'TGIF!'}
+ Tempfile.open('fun.yml') do |io|
+ assert_equal io, Psych.dump(hash, io)
+ io.rewind
+ assert_equal Psych.dump(hash), io.read
+ end
+ end
+
+ def test_dump_io
+ hash = {'hello' => 'TGIF!'}
+ stringio = StringIO.new ''
+ assert_equal stringio, Psych.dump(hash, stringio)
+ assert_equal Psych.dump(hash), stringio.string
+ end
+
def test_simple
assert_equal 'foo', Psych.load("--- foo\n")
end