YAML serialization of exceptions

  • Thread starter John-Mason P. Shackelford
  • Start date
J

John-Mason P. Shackelford

Why does the YAML library add a 'mesg' instance variable instead of
re-implementing Exception#message to return @message? Any reason why
we don't preserve the backtrace as well? (Relevant YAML code excepted
below.)

# File yaml/rubytypes.rb
YAML.add_ruby_type( /^exception/ ) { |type, val|
type, obj_class =3D YAML.read_type_class( type, Exception )
o =3D YAML.object_maker( obj_class, { 'mesg' =3D> val.delete( 'message'=
) } )
val.each_pair { |k,v|
=09=09o.instance_variable_set("@#{k}", v)
=09}
=09o
}

# File yaml/rubytypes.rb, line 119
def Exception.yaml_new( klass, tag, val )
o =3D YAML.object_maker( klass, { 'mesg' =3D> val.delete( 'message'=
) } )
val.each_pair do |k,v|
o.instance_variable_set("@#{k}", v)
end
o
end


Is the best way for me to support this functionality for a particular
exception to call YAML.add_ruby_type() and to implement #to_yaml and
#yaml_new methods on my exception?

Thanks!


John-Mason Shackelford

Software Developer
Pearson Educational Measurement

2510 North Dodge St.
Iowa City, IA 52245
ph. 319-354-9200x6214
(e-mail address removed)
http://pearsonedmeasurement.com
 
J

John-Mason P. Shackelford

Comments on the following alternative?

# Add support for serialization
class Exception
=09def to_yaml( opts =3D {} )
=09=09YAML::quick_emit( self.object_id, opts ) { |out|
out.map( self.to_yaml_type ) { |map|
map.add( 'message', self.message )
map.add( 'backtrace', self.backtrace )
=09=09=09=09to_yaml_properties.each { |m|
map.add( m[1..-1], instance_variable_get( m ) )
}
}
=09=09}
=09end
end

YAML.add_ruby_type( /^exception/ ) { |type, val|
type, obj_class =3D YAML.read_type_class( type, Exception )
o =3D YAML.object_maker( obj_class, val )
val.each_pair { |k,v|
=09=09o.instance_variable_set("@#{k}", v)
=09}
=09class << o
=09 attr_reader :message, :backtrace
=09end
=09o
}

John-Mason Shackelford

Software Developer
Pearson Educational Measurement

2510 North Dodge St.
Iowa City, IA 52245
ph. 319-354-9200x6214
(e-mail address removed)
http://pearsonedmeasurement.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top