aboutsummaryrefslogtreecommitdiffstats
path: root/activejob/lib/active_job/serializers/global_id_serializer.rb
blob: 84ed33ef9913f3b51e368564e86ca8f63f1ac156 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# frozen_string_literal: true

module ActiveJob
  module Serializers
    # Provides methods to serialize and deserialize objects which mixes `GlobalID::Identification`,
    # including `ActiveRecord::Base` models
    class GlobalIDSerializer < BaseSerializer
      class << self
        def serialize(object)
          { GLOBALID_KEY => object.to_global_id.to_s }
        rescue URI::GID::MissingModelIdError
          raise SerializationError, "Unable to serialize #{object.class} " \
            "without an id. (Maybe you forgot to call save?)"
        end

        def deserialize(hash)
          GlobalID::Locator.locate(hash[GLOBALID_KEY])
        end

        def deserialize?(argument)
          argument.is_a?(Hash) && argument[GLOBALID_KEY]
        end

        private

        def klass
          GlobalID::Identification
        end
      end
    end
  end
end