简体   繁体   中英

Trying to implement Rails ActiveJob Serializer

I am trying to implement an ActiveJob Serializer so that I can deliver email with the deliver_later method. Examples I see of this say that I should extend the class

ActiveJob::Serializers::ObjectSerializer 

and configure the serializer in my application config

Rails.application.config.active_job.custom_serializers << MySerializer.

My application is a bit different, in that the configuration lives in namespace (cannot change this) and this is causing some problems. I have tried the following:

class MySerializer < ActiveJob::Serializer::ObjectSerializer
---
end

as well as

module MyNamespace
  class MySerializer < ActiveJob::Serializer::ObjectSerializer
  ---
  end
end

I have put the serializer under app/serializers .

I have tried to set the Active Job setting both with:

module MyNamespace
  class Application < Rails::Application
    config.active_job.custom_serializers << MySerializer
  end 
end

which is where all other application config setting are made, which ends up with the error:

uninitialized constant MyNamespace::Application::MySerializer (NameError)

If I pull it completely outside of the namespace with

Rails.application.config.active_job.custom_serializers << MySerializer

I get the error message:

uninitialized constant MySerializer (NameError)

Any ideas regarding what I am doing wrong that is causing my serializer to not be found?

Namespacing in serializers, active job or not, works just fine, but you have to identify the namespace in each place that its called.

Config:

Rails.application.config.active_job.custom_serializers << MyNamespace::MySerializer

Location:

app/serializers/my_namespace/my_serializer.rb

Job:

def perform(*args)
  # do some stuff with your serialized item by calling- note the method serialize here is just a default and you could have whatever you need here

  MyNamespace::MySerializer.serialize(args[0]).serializeable_hash
end    

Inheritance:

module MyNamespace
  class MySerializer < ActiveJob::Serializers::ObjectSerializer
    def serialize(object)
      #....
    end
  end
end

# note that in your example, Serializer was singular instead of plural

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM