yaml, time, datetime

462 views
Skip to first unread message

Glenn Little

unread,
Sep 29, 2008, 9:20:48 PM9/29/08
to sdr...@googlegroups.com
It appears that the roundtrip of a DateTime object to yaml and
back via YAML.dump and YAML.load results in a Time object, instead
of a DateTime object:

>> dt = DateTime.now
>> temp = YAML.dump(dt)
>> restored = YAML.load(temp)
>> restored.class
=> Time

Is there any more elegant way to deal with this other than
hard-coding a conversion back to DateTime:

>> temp = YAML.dump(dt)
>> restored = YAML.load(temp).to_datetime
>> restored.class
=> DateTime

?

Thanks!

-glenn

Brian Chapados

unread,
Sep 30, 2008, 3:58:43 PM9/30/08
to SD Ruby
Check out the source code for lib/yaml/rubytypes.rb in the ruby source
tree. Ruby transforms a YAML timestamp[1] into an instance of Time.
You can add support for DateTime by defining a few methods. This naive
approach[2] might work, but there may be caveats. Look at the yaml
methods for Time. You will need to do a little more work if you need
to support micro seconds, since that info is not encoded in the string
representation of a DateTime.

[1]: http://yaml.org/type/timestamp.html
[2]: http://gist.github.com/13926
Reply all
Reply to author
Forward
0 new messages