Ruby on Rails 3: How to override/change as_json serialization for ActiveSupport::TimeWithZone?
When Rails3 serializes ActiveSupport::TimeWithZone to json that dates look something like this:
"2011-07-20T23:59:00-07:00"
... it should be ...
"2011-07-20T23:59:00-0700"
That last colon is problematic when trying to convert that string using standard date formatting patterns ... none of them account for the use of a colon!
So my question is, "How do I override/change the serialization for Tim开发者_Go百科eWithZone so that as_json returns a valid string that can be understood using the standard date format patterns?"
Right now I have to strip that last colon out in my client app but that just seems pooch.
It is a monkey patch, but hey it is Ruby and that is allowed.
module ActiveSupport
class TimeWithZone
def to_json
super.gsub(/:(?!.*:)/,'')
end
end
end
Tested by running:
Time.zone = 'Eastern Time (US & Canada)'
Time.zone.now.to_json # Outputs -> 2011-09-22T16:46:28-0400
精彩评论