Slightly better YAMLization of Ruby Exceptions.
Consider the following irb session:
Code (ruby)
-
-
irb(main):001:0> e = Exception.new("Jerk!")
-
=> #<Exception: Jerk!>
-
irb(main):002:0> e.message
-
=> "Jerk!"
-
irb(main):003:0> require ‘yaml’
-
=> true
-
irb(main):004:0> YAML.load(e.to_yaml).message
-
=> "Exception"
-
That sucks. Where did the “Jerk!” go? YAML ate it. If you include this code, you can keep your “Jerk!”:
Code (ruby)
-
-
cpm@juno:~/helpticket-dev/trunk$ cat lib/better_exception_yaml.rb
-
require ‘yaml’
-
-
class Exception
-
def Exception.yaml_new( klass, tag, val )
-
o = YAML.object_maker( klass, {})
-
val.each_pair do |k,v|
-
o.instance_variable_set("@#{k}", v)
-
end
-
o.exception(val["message"])
-
end
-
end
-
-
cpm@juno:~/helpticket-dev/trunk$ irb
-
irb(main):001:0> require ‘lib/better_exception_yaml’
-
=> true
-
irb(main):002:0> YAML.load(Exception.new("JERK").to_yaml).message
-
=> "JERK"
-
It still sucks because the backtrace is not preserved, but that’s because Exception#to_yaml doesn’t serialize that information. YAML was storing the message, but by default it stores it into a @mesg instance variable instead. Quite odd.
I wasn’t inclined enough to read up on the right way to yamlize new data. Maybe later I’ll add backtracing.