From d2c094aa5081677bf537a1553d0a756fcafcfb4e Mon Sep 17 00:00:00 2001 From: bogdanvlviv Date: Sat, 17 Feb 2018 00:15:11 +0200 Subject: [PATCH] Add argument serializer `TimeWithZoneSerializer` The serializer serializes an instance of `ActiveSupport::TimeWithZone`. The serializer deserializes value to `ActiveSupport::TimeWithZone` if possible. --- activejob/lib/active_job/serializers.rb | 6 ++++-- .../serializers/time_with_zone_serializer.rb | 21 +++++++++++++++++++ .../test/cases/argument_serialization_test.rb | 8 +++++++ 3 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 activejob/lib/active_job/serializers/time_with_zone_serializer.rb diff --git a/activejob/lib/active_job/serializers.rb b/activejob/lib/active_job/serializers.rb index 9930ae0823..7ee63a8a87 100644 --- a/activejob/lib/active_job/serializers.rb +++ b/activejob/lib/active_job/serializers.rb @@ -12,9 +12,10 @@ module ActiveJob autoload :ObjectSerializer autoload :SymbolSerializer autoload :DurationSerializer - autoload :DateSerializer - autoload :TimeSerializer autoload :DateTimeSerializer + autoload :DateSerializer + autoload :TimeWithZoneSerializer + autoload :TimeSerializer mattr_accessor :_additional_serializers self._additional_serializers = Set.new @@ -57,6 +58,7 @@ module ActiveJob DurationSerializer, DateTimeSerializer, DateSerializer, + TimeWithZoneSerializer, TimeSerializer end end diff --git a/activejob/lib/active_job/serializers/time_with_zone_serializer.rb b/activejob/lib/active_job/serializers/time_with_zone_serializer.rb new file mode 100644 index 0000000000..43017fc75b --- /dev/null +++ b/activejob/lib/active_job/serializers/time_with_zone_serializer.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true + +module ActiveJob + module Serializers + class TimeWithZoneSerializer < ObjectSerializer # :nodoc: + def serialize(time) + super("value" => time.iso8601) + end + + def deserialize(hash) + Time.iso8601(hash["value"]).in_time_zone + end + + private + + def klass + ActiveSupport::TimeWithZone + end + end + end +end diff --git a/activejob/test/cases/argument_serialization_test.rb b/activejob/test/cases/argument_serialization_test.rb index ff6ac6fc43..1daccd40c4 100644 --- a/activejob/test/cases/argument_serialization_test.rb +++ b/activejob/test/cases/argument_serialization_test.rb @@ -102,6 +102,14 @@ class ArgumentSerializationTest < ActiveSupport::TestCase assert_instance_of ActiveSupport::HashWithIndifferentAccess, perform_round_trip([indifferent_access]).first end + test "should maintain time with zone" do + Time.use_zone "Alaska" do + time_with_zone = Time.new(2002, 10, 31, 2, 2, 2).in_time_zone + assert_instance_of ActiveSupport::TimeWithZone, perform_round_trip([time_with_zone]).first + assert_arguments_unchanged time_with_zone + end + end + test "should disallow non-string/symbol hash keys" do assert_raises ActiveJob::SerializationError do ActiveJob::Arguments.serialize [ { 1 => 2 } ]