Skip to content
Browse files

Take into account current time zone when serializing datetime values [#…

…6096 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
  • Loading branch information...
1 parent 07b0e59 commit f572a02b94ce85bb8db64e838aa159cf3ef4b1fa @michaeldv michaeldv committed with josevalim Dec 8, 2010
View
1 activemodel/lib/active_model/serializers/xml.rb
@@ -17,6 +17,7 @@ class Attribute #:nodoc:
def initialize(name, serializable, raw_value=nil)
@name, @serializable = name, serializable
+ raw_value = raw_value.in_time_zone if raw_value.respond_to?(:in_time_zone)
@pixeltrix
Ruby on Rails member
pixeltrix added a note Jun 24, 2012

Would this be better as acts_like?(:time)? Is in_time_zone meant to act as a coercion discriminator like to_ary and to_str?

The reason is that whilst looking at issues that people have with Active Support's date & time features one of the problems I've come across is that some people use Date#to_time_in_current_zone on DateTime instances (DateTime inherits from Date) and end up losing the time component.

To fix this I was looking at deprecating to_time_in_current_zone and adding in_time_zone - that way DateTime's implementation overrides Dates. I was also looking at adding String#in_time_zone for consistency. Obviously both of these would conflict with this line and the concept of using in_time_zone as a discriminator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@value = raw_value || @serializable.send(name)
@type = compute_type
end
View
21 activerecord/test/cases/xml_serialization_test.rb
@@ -4,6 +4,7 @@
require 'models/author'
require 'models/comment'
require 'models/company_in_module'
+require 'models/toy'
class XmlSerializationTest < ActiveRecord::TestCase
def test_should_serialize_default_root
@@ -83,6 +84,26 @@ def test_should_serialize_hash
end
end
+class DefaultXmlSerializationTimezoneTest < ActiveRecord::TestCase
+ def test_should_serialize_datetime_with_timezone
+ timezone, Time.zone = Time.zone, "Pacific Time (US & Canada)"
+
+ toy = Toy.create(:name => 'Mickey', :updated_at => Time.utc(2006, 8, 1))
+ assert_match %r{<updated-at type=\"datetime\">2006-07-31T17:00:00-07:00</updated-at>}, toy.to_xml
+ ensure
+ Time.zone = timezone
+ end
+
+ def test_should_serialize_datetime_with_timezone_reloaded
+ timezone, Time.zone = Time.zone, "Pacific Time (US & Canada)"
+
+ toy = Toy.create(:name => 'Minnie', :updated_at => Time.utc(2006, 8, 1)).reload
+ assert_match %r{<updated-at type=\"datetime\">2006-07-31T17:00:00-07:00</updated-at>}, toy.to_xml
+ ensure
+ Time.zone = timezone
+ end
+end
+
class NilXmlSerializationTest < ActiveRecord::TestCase
def setup
@xml = Contact.new.to_xml(:root => 'xml_contact')

0 comments on commit f572a02

Please sign in to comment.
Something went wrong with that request. Please try again.