From 4cfc467594da86090efa63f1852fb82df9458c2b Mon Sep 17 00:00:00 2001 From: Parker Selbert Date: Tue, 16 Jul 2013 16:16:33 -0400 Subject: Customize subsecond digits when encoding DateWithTime The subsecond fraction digits had been hardcoded to 3. This forced all timestamps to include the subsecond digits with no way to customize the value. While the subsecond format is part of the ISO8601 spec, it is not adhered to by all parsers (notably mobile clients). This adds the ability to customize the number of digits used, optionally setting them to 0 in order to eliminate the subsecond fraction entirely: ActiveSupport::JSON::Encoding.subsecond_fraction_digits = 0 --- activesupport/test/core_ext/time_with_zone_test.rb | 29 ++++++++++++++++------ 1 file changed, 22 insertions(+), 7 deletions(-) (limited to 'activesupport/test') diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb index 43fe572bfc..4ea8d2bed6 100644 --- a/activesupport/test/core_ext/time_with_zone_test.rb +++ b/activesupport/test/core_ext/time_with_zone_test.rb @@ -67,17 +67,25 @@ class TimeWithZoneTest < ActiveSupport::TestCase end def test_to_json_with_use_standard_json_time_format_config_set_to_false - old, ActiveSupport.use_standard_json_time_format = ActiveSupport.use_standard_json_time_format, false - assert_equal "\"1999/12/31 19:00:00 -0500\"", ActiveSupport::JSON.encode(@twz) - ensure - ActiveSupport.use_standard_json_time_format = old + with_standard_json_time_format(false) do + assert_equal "\"1999/12/31 19:00:00 -0500\"", ActiveSupport::JSON.encode(@twz) + end end def test_to_json_with_use_standard_json_time_format_config_set_to_true - old, ActiveSupport.use_standard_json_time_format = ActiveSupport.use_standard_json_time_format, true - assert_equal "\"1999-12-31T19:00:00.000-05:00\"", ActiveSupport::JSON.encode(@twz) + with_standard_json_time_format(true) do + assert_equal "\"1999-12-31T19:00:00.000-05:00\"", ActiveSupport::JSON.encode(@twz) + end + end + + def test_to_json_with_custom_subsecond_resolution + with_standard_json_time_format(true) do + ActiveSupport::JSON::Encoding.subsecond_fraction_digits = 0 + + assert_equal "\"1999-12-31T19:00:00-05:00\"", ActiveSupport::JSON.encode(@twz) + end ensure - ActiveSupport.use_standard_json_time_format = old + ActiveSupport::JSON::Encoding.subsecond_fraction_digits = nil end def test_to_json_when_wrapping_a_date_time @@ -814,6 +822,13 @@ class TimeWithZoneTest < ActiveSupport::TestCase ensure old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ') end + + def with_standard_json_time_format(boolean = true) + old, ActiveSupport.use_standard_json_time_format = ActiveSupport.use_standard_json_time_format, boolean + yield + ensure + ActiveSupport.use_standard_json_time_format = old + end end class TimeWithZoneMethodsForTimeAndDateTimeTest < ActiveSupport::TestCase -- cgit v1.2.3