1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/activejob/lib/active_job/serializers/object_serializer.rb
Rafael Mendonça França 69645cba72 Simplify the implementation of custom argument serializers
We can speed up things for the supported types by keeping the code in the
way it was.

We can also avoid to loop trough all serializers in the deserialization by
trying to access the class already in the Hash.

We could also speed up the custom serialization if we define the class
that is going to be serialized when registering the serializers, but
that will remove the possibility of defining a serialzer for a
superclass and have the subclass serialized using it.
2018-02-14 13:10:08 -05:00

54 lines
1.3 KiB
Ruby

# frozen_string_literal: true
module ActiveJob
module Serializers
# Base class for serializing and deserializing custom times.
#
# Example
#
# class MoneySerializer < ActiveJob::Serializers::ObjectSerializer
# def serialize(money)
# super("cents" => money.cents, "currency" => money.currency)
# end
#
# def deserialize(hash)
# Money.new(hash["cents"], hash["currency"])
# end
#
# private
#
# def klass
# Money
# end
# end
class ObjectSerializer
include Singleton
class << self
delegate :serialize?, :serialize, :deserialize, to: :instance
end
# Determines if an argument should be serialized by a serializer.
def serialize?(argument)
argument.is_a?(klass)
end
# Serializes an argument to a JSON primitive type.
def serialize(hash)
{ Arguments::OBJECT_SERIALIZER_KEY => self.class.name }.merge!(hash)
end
# Deserilizes an argument form a JSON primiteve type.
def deserialize(_argument)
raise NotImplementedError
end
protected
# The class of the object that will be serialized.
def klass
raise NotImplementedError
end
end
end
end