Created
June 1, 2012 17:27
-
-
Save jrafanie/2853827 to your computer and use it in GitHub Desktop.
Psych hack to serialize instance variables in a Hash subclass.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
From 4df445619ad6940058bb5a80f569e21f8ea370f6 Mon Sep 17 00:00:00 2001 | |
From: Joe Rafaniello <jrafanie@gmail.com> | |
Date: Fri, 1 Jun 2012 12:17:40 -0400 | |
Subject: [PATCH] Hack to serialize instance variables in a Hash subclass. | |
--- | |
lib/psych/visitors/to_ruby.rb | 2 ++ | |
lib/psych/visitors/yaml_tree.rb | 5 +++++ | |
test/psych/test_hash.rb | 10 ++++++++++ | |
3 files changed, 17 insertions(+) | |
diff --git a/lib/psych/visitors/to_ruby.rb b/lib/psych/visitors/to_ruby.rb | |
index eb4bab7..b594e06 100644 | |
--- a/lib/psych/visitors/to_ruby.rb | |
+++ b/lib/psych/visitors/to_ruby.rb | |
@@ -268,6 +268,8 @@ module Psych | |
else | |
hash[key] = accept(v) | |
end | |
+ elsif key.to_s[0..5] == "__iv__" | |
+ hash.instance_variable_set(key.to_s[6..-1], accept(v)) | |
else | |
hash[key] = accept(v) | |
end | |
diff --git a/lib/psych/visitors/yaml_tree.rb b/lib/psych/visitors/yaml_tree.rb | |
index 646fed7..c6a9d86 100644 | |
--- a/lib/psych/visitors/yaml_tree.rb | |
+++ b/lib/psych/visitors/yaml_tree.rb | |
@@ -293,6 +293,11 @@ module Psych | |
accept v | |
end | |
+ o.instance_variables.each do |m| | |
+ accept "__iv__#{m}" | |
+ accept o.instance_variable_get(m) | |
+ end | |
+ | |
@emitter.end_mapping | |
end | |
diff --git a/test/psych/test_hash.rb b/test/psych/test_hash.rb | |
index 4bd4edf..b000226 100644 | |
--- a/test/psych/test_hash.rb | |
+++ b/test/psych/test_hash.rb | |
@@ -5,6 +5,10 @@ module Psych | |
class X < Hash | |
end | |
+ class Y < Hash | |
+ attr_accessor :val | |
+ end | |
+ | |
def setup | |
super | |
@hash = { :a => 'b' } | |
@@ -16,6 +20,12 @@ module Psych | |
assert_equal X, x.class | |
end | |
+ def test_subclass_with_attributes | |
+ y = Psych.load Psych.dump Y.new.tap {|y| y.val = 1} | |
+ assert_equal Y, y.class | |
+ assert_equal 1, y.val | |
+ end | |
+ | |
def test_map | |
x = Psych.load "--- !map:#{X} { }\n" | |
assert_equal X, x.class | |
-- | |
1.7.10.1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment