From c330b9e93fdf5eb15aea29ede9dd017c037b3942 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 7 Oct 2009 11:52:54 -0700 Subject: structs will round trip --- lib/psych/ruby.rb | 3 +-- lib/psych/visitors/to_ruby.rb | 14 ++++++++++++++ lib/psych/visitors/yast_builder.rb | 11 +++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/psych/ruby.rb b/lib/psych/ruby.rb index f226c84..f564565 100644 --- a/lib/psych/ruby.rb +++ b/lib/psych/ruby.rb @@ -4,8 +4,7 @@ require 'date' [ Object, String, Class, Hash, Array, NilClass, Float, FalseClass, TrueClass, - Range, Complex, Rational, Date, Time, Regexp, Exception - # Struct + Range, Complex, Rational, Date, Time, Regexp, Exception, Struct ].each do |klass| klass.send(:remove_method, :to_yaml) rescue NameError end diff --git a/lib/psych/visitors/to_ruby.rb b/lib/psych/visitors/to_ruby.rb index d00f72a..1d5bd4b 100644 --- a/lib/psych/visitors/to_ruby.rb +++ b/lib/psych/visitors/to_ruby.rb @@ -77,6 +77,20 @@ module Psych def visit_Psych_Nodes_Mapping o case o.tag + when /!ruby\/struct(:.*)?$/ + klassname = $1 + h = Hash[*o.children.map { |c| accept c }].to_a + + if klassname && klassname.length > 1 + s = klassname.sub(/^:/,'').split('::').inject(Object) { |k,o| + k.const_get(o) + }.allocate + h.each { |k,v| s.send("#{k}=", v) } + s + else + Struct.new(*h.map { |k,v| k.to_sym }).new(*h.map { |k,v| v }) + end + when '!ruby/range' h = Hash[*o.children.map { |c| accept c }] Range.new(h['begin'], h['end'], h['excl']) diff --git a/lib/psych/visitors/yast_builder.rb b/lib/psych/visitors/yast_builder.rb index 914a891..6100264 100644 --- a/lib/psych/visitors/yast_builder.rb +++ b/lib/psych/visitors/yast_builder.rb @@ -21,6 +21,17 @@ module Psych raise TypeError, "Can't dump #{target.class}" end + def visit_Struct o + tag = ['!ruby/struct', o.class.name].compact.join(':') + + @stack.push append Nodes::Mapping.new(nil, tag, false) + o.members.each do |member| + accept member + accept o[member] + end + @stack.pop + end + def visit_Exception o @stack.push append Nodes::Mapping.new(nil, '!ruby/exception', false) ['message', o.message].each do |m| -- cgit v1.2.3