1unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED 2 require 'json' 3end 4 5# Time serialization/deserialization 6class Time 7 8 # Deserializes JSON string by converting time since epoch to Time 9 def self.json_create(object) 10 if usec = object.delete('u') # used to be tv_usec -> tv_nsec 11 object['n'] = usec * 1000 12 end 13 if instance_methods.include?(:tv_nsec) 14 at(object['s'], Rational(object['n'], 1000)) 15 else 16 at(object['s'], object['n'] / 1000) 17 end 18 end 19 20 # Returns a hash, that will be turned into a JSON object and represent this 21 # object. 22 def as_json(*) 23 nanoseconds = [ tv_usec * 1000 ] 24 respond_to?(:tv_nsec) and nanoseconds << tv_nsec 25 nanoseconds = nanoseconds.max 26 { 27 JSON.create_id => self.class.name, 28 's' => tv_sec, 29 'n' => nanoseconds, 30 } 31 end 32 33 # Stores class name (Time) with number of seconds since epoch and number of 34 # microseconds for Time as JSON string 35 def to_json(*args) 36 as_json.to_json(*args) 37 end 38end 39