0s r Fun
0s r Fun

Reputation: 51

ActiveJob custom serializer - uninitialized constant NameError

I am trying to add a custom serializer to ActiveJob following the ActiveJob Rails Guide. I have the following class, originally in the file app/lib/money_serializer.rb,

  class MoneySerializer < ActiveJob::Serializers::ObjectSerializer
  # ... 
  end

And in config/application.rb

  # ...
  config.active_job.custom_serializers << MoneySerializer
  # ...

I keep getting uninitialized constant MoneySerializer (NameError) which suggests to me that the Serializer is not being loaded on boot and tried placing it in different locations (including under config/initializers) without any luck.

What am I missing here? Where should I place an ActiveJob serializer?

Upvotes: 4

Views: 997

Answers (2)

Alexander Makarenko
Alexander Makarenko

Reputation: 309

Based on the discussion here, the issue is best solved as follows:

Rails.autoloaders.main.ignore(Rails.root.join("app/serializers"))

Dir[Rails.root.join("app/serializers/**/*.rb")].each { |f| require f }

Rails.application.config.active_job.custom_serializers << MoneySerializer

Update: In Rails 7, you can simply add the following to config/application.rb:

config.autoload_once_paths += Dir[Rails.root.join("app/serializers")]

Upvotes: 6

0s r Fun
0s r Fun

Reputation: 51

If it helps anyone,

It seems to work when I put both the Serializer and the config in an initializer

  class MoneySerializer < ActiveJob::Serializers::ObjectSerializer
  # ... 
  end

  config.active_job.custom_serializers << MoneySerializer

Feels very odd to have a class here. Any other suggestions?

Upvotes: 1

Related Questions