Last active
April 8, 2018 16:53
-
-
Save cabo/fb2f6ea30f1158b63e6c5649beabfc75 to your computer and use it in GitHub Desktop.
Play around with CBOR for Time and DateTime in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'cbor' | |
# Assume that the cbor-diag gem is installed, but don't use it directly | |
def pretty(item) | |
IO.popen("cbor2pretty.rb", "wb") {|io| io.write(item)} | |
end | |
puts "# Show that the default Time representation is Tag 1" | |
t = Time.now | |
p t | |
pretty t.to_cbor | |
require 'date' | |
puts "# Make us a DateTime out of that Time" | |
dt = t.to_datetime | |
p dt | |
puts dt.to_s | |
puts "# Out of the box, to_cbor fails for DateTime" | |
begin | |
pretty dt.to_cbor | |
rescue => e | |
p e | |
end | |
# This module can be used to define to_cbor for Date | |
module DateTimeAsRfc3337 | |
def to_cbor | |
CBOR::Tagged.new(0, rfc3339).to_cbor | |
end | |
end | |
puts "# So let's make us a module DateTimeAsRfc3337 and extend with that" | |
dt.extend(DateTimeAsRfc3337) | |
pretty dt.to_cbor | |
puts "# Show how a different timezone is serialized" | |
pretty dt.new_offset.extend(DateTimeAsRfc3337).to_cbor | |
# This module can be used to define to_cbor for anything that supports to_datetime | |
module TimeAsRfc3337 | |
def to_cbor | |
CBOR::Tagged.new(0, to_datetime.rfc3339).to_cbor | |
end | |
end | |
puts "# ... and a module TimeAsRfc3337 and extend the Time object with that" | |
t.extend(TimeAsRfc3337) | |
pretty t.to_cbor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment