aboutsummaryrefslogtreecommitdiffstats
path: root/activejob/lib/active_job/serializers/global_id_serializer.rb
blob: ec20cf04f7b3b46da82c2140c79bb5f9dd2e95e3 (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 < ObjectSerializer
      class << self
        def serialize(object)
          { 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[key])
        end

        def key
          "_aj_globalid"
        end

        private

        def klass
          GlobalID::Identification
        end
      end
    end
  end
end