DmitryTsepelev / store_model

Work with JSON-backed attributes as ActiveRecord-ish models
MIT License
1.09k stars 89 forks source link

ActiveJob::SerializationError: #184

Open Hammam94 opened 2 months ago

Hammam94 commented 2 months ago

i am using paper_trail-background gem to version the records in the background your gem is not compatible with activejob as it raises the following issue ActiveJob::SerializationError: Unsupported argument type: Inventory::JsonbModels::Telephone Here is the store model class

module Inventory
  module JsonbModels
    class Telephone
      include StoreModel::Model

      enum :type, {
        fax: 'fax',
        phone: 'phone'
      }, default: :phone

      attribute :number, :string
    end
  end
end

any solution for that error

DmitryTsepelev commented 2 months ago

Hey! I've never used this combination of gems before, you'll have to figure out the solution and let me know 🙂 Probably you just need to define a serialization method (https://api.rubyonrails.org/classes/ActiveJob/SerializationError.html)

Hammam94 commented 1 month ago

i solved this by adding this custom serializer in the initializers folder please check it and tell me what do you think

module ActiveJob
  module Serializers
    class StoreModelSerializer < ActiveJob::Serializers::ObjectSerializer
      def serialize?(argument)
        argument.is_a?(StoreModel::Model)
      end

      def serialize(store_model)
        super(
          'attributes' => store_model.attributes,
          'class' => store_model.class.name
        )
      end

      def deserialize(hash)
        klass = hash['class'].constantize
        klass.new(hash['attributes'])
      end
    end
  end
end

ActiveJob::Serializers.add_serializers(ActiveJob::Serializers::StoreModelSerializer)