From 7cff0bed26b438e0ca2727bba5a0c52d3a40c443 Mon Sep 17 00:00:00 2001 From: Andrew Marshall Date: Tue, 20 May 2014 14:26:18 -0400 Subject: [PATCH] Fix loading objects with instance variables named "null" Do so by always interpreting mapping keys in an object as symbols rather than strings. When interpreted as a string it becomes nil which is then coerced to a string ("") and then tries to set the ivar "@" rather than "@null", raising the following error: > NameError: `@' is not allowed as an instance variable name --- lib/psych/visitors/yaml_tree.rb | 2 +- test/psych/test_object.rb | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/psych/visitors/yaml_tree.rb b/lib/psych/visitors/yaml_tree.rb index ff0fcd20..29d66af0 100644 --- a/lib/psych/visitors/yaml_tree.rb +++ b/lib/psych/visitors/yaml_tree.rb @@ -512,7 +512,7 @@ def dump_ivars target ivars = find_ivars target ivars.each do |iv| - @emitter.scalar("#{iv.to_s.sub(/^@/, '')}", nil, nil, true, false, Nodes::Scalar::ANY) + @emitter.scalar("#{iv.to_s.sub(/^@/, ':')}", nil, nil, true, false, Nodes::Scalar::ANY) accept target.instance_variable_get(iv) end end diff --git a/test/psych/test_object.rb b/test/psych/test_object.rb index 5e3ce829..5d3114c8 100644 --- a/test/psych/test_object.rb +++ b/test/psych/test_object.rb @@ -19,6 +19,14 @@ def initialize parent end end + class WithNull + attr_accessor :null + + def initialize + @null = true + end + end + class TestObject < TestCase def test_dump_with_tag tag = Tagged.new @@ -40,5 +48,12 @@ def test_cyclic_references assert_instance_of(Foo, loaded) assert_equal loaded, loaded.parent end + + def test_null_named_ivar + original = WithNull.new + loaded = Psych.load(Psych.dump(original)) + + assert_equal(original.null, loaded.null) + end end end