Skip to content

@jrafanie /gist:2853827
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Psych hack to serialize instance variables in a Hash subclass.
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
Something went wrong with that request. Please try again.