public
Created

Psych hack to serialize instance variables in a Hash subclass.

  • Download Gist
gistfile1.diff
Diff
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.