A straightforward approach is to monkey patch Time, although I'm not fond of doing that, especially to core classes
There's no JSON format for dates, as far as JSON cares they're just strings. Most languages understand ISO 8601, and that's what Time#to_json
produces. So long as Time#to_json
continues to produce an ISO 8601 datetime you'll remain backwards compatible.
require 'json'
require 'time' # for Time#iso8601 and Time.parse
class Time
def to_json
return self.iso8601(6).to_json
end
end
time = Time.at(1000.123456)
puts "Before: #{time.iso8601(6)}"
json_time = Time.at(1000.123456).to_json
puts "As JSON: #{json_time}"
# Demonstrate round tripping.
puts "Round trip: #{Time.parse(JSON.parse(json_time)).iso8601(6)}"
Before: 1969-12-31T16:16:40.123456-08:00
As JSON: "1969-12-31T16:16:40.123456-08:00"
Round trip: 1969-12-31T16:16:40.123456-08:00
If you're not comfortable with monkey patching globally, you can monkey patch in isolation by implementing around
.
class Time
require 'time'
require 'json'
def precise_to_json(*args)
return iso8601(6).to_json(*args)
end
alias_method :original_to_json, :to_json
end
module PreciseJson
def self.around
# Swap in our precise_to_json as Time#to_json
Time.class_eval {
alias_method :to_json, :precise_to_json
}
# This block will use Time#precise_to_json as Time#to_json
yield
# Always put the original Time#to_json back.
ensure
Time.class_eval {
alias_method :to_json, :original_to_json
}
end
end
obj = {
time: Time.at(1000.123456),
string: "Basset Hounds Got Long Ears"
}
puts "Before: #{obj.to_json}"
PreciseJson.around {
puts "Around: #{obj.to_json}"
}
puts "After: #{obj.to_json}"
begin
PreciseJson.around {
raise Exception
}
rescue Exception
end
puts "After exception: #{obj.to_json}"
Before: {"time":"1969-12-31 16:16:40 -0800","string":"Basset Hounds Got Long Ears"}
Around: {"time":"1969-12-31T16:16:40.123456-08:00","string":"Basset Hounds Got Long Ears"}
After: {"time":"1969-12-31 16:16:40 -0800","string":"Basset Hounds Got Long Ears"}
After exception: {"time":"1969-12-31 16:16:40 -0800","string":"Basset Hounds Got Long Ears"}