Ruby DateTime YAML extensions
"Sam Granieri, Jr" <sam-HbX/[email protected]>
| Newsgroups | gmane.text.yaml.general |
|---|---|
| Message-ID | <[email protected]> |
I'm writing a plugin for a rails app to allow yaml to serialize and
deserialize DateTimes, especially datetimes that are beyond the range
of what a Time Object can store
Basically, I want
require 'date'
require 'time'
require 'yaml'
YAML::load(DateTime.now.to_yaml).class
to return DateTime instead of time.
Here's the ruby code I came up with
require 'yaml'
require 'date'
require 'time'
class DateTime
yaml_as "tag:yaml.org,2002:timestamp"
yaml_as "tag:ruby.yaml.org,2002:#{self}"
def to_yaml( opts = {} )
YAML::quick_emit( nil, opts ) do |out|
out.scalar(taguri,self.to_s, :plain)
end
end
def self.yaml_new( klass, tag, val )
DateTime.parse(val)
end
end
And here's the test code
class YamlDatetimeFixTest < Test::Unit::TestCase
def setup
@fardate = DateTime.new(1999,1,1)
end
# Replace this with your real tests.
def test_this_plugin
assert_equal(DateTime,YAML::load(DateTime.now.to_yaml).class)
yml = @fardate.to_yaml
puts yml
begin
res = YAML::load(yml)
puts res.to_s
rescue Exception => e
puts "fail"
end
assert_equal(res.class, DateTime)
end
end
I get these results:
Started
--- !ruby/DateTime 1999-01-01T00:00:00+00:00
1999-01-01T00:00:00+00:00
.
Finished in 0.012187 seconds.
1 tests, 2 assertions, 0 failures, 0 errors
I think I have everything down, but the one thing that just seems to
bug me is my DateTime.to_yaml line of code outputs
--- !ruby/DateTime 1999-01-01T00:00:00+00:00
instead of
--- 1999-01-01T00:00:00+00:00
Is there a way to fix this? I could really welcome the help.
Thanks!
I'm in irc.freenode.net#yaml as samgranieri as well.
-------------------------------------------------------------------------
This SF.Net email is sponsored by the Moblin Your Move Developer's challenge
Build the coolest Linux based applications with Moblin SDK & win great prizes
Grand prize is a trip for two to an Open Source event anywhere in the world
http://moblin-contest.org/redirect.php?banner_id=100&url=/