I am implementing a singleton class/module in Rails 6 application using Zeitwerk loader.
# app/lib/mynamespace/mymodel.rb
module Mynamespace
module Mymodel
class << self
attr_accessor :client
end
def self.client
@client ||= "default_value"
end
def self.client=(client)
@client = client
end
end
Singleton class is initialized in
# config/initializers/mymodel.rb
Mynamespace::Mymodel.client = "my_custom_value"
# Mynamespace::Mymodel.client - this returns correct value
Then when I use the singleton class in a controller
# app/controllers/mycontroller.rb
client = Mynamespace::Mymodel.client
it returns an empty object as it was not initialized: client == "default_value" but should be "my_custom_value".
Log shows errors
DEPRECATION WARNING: Initialization autoloaded the constants Mynamespace::Mymodel
Autoloading during initialization is going to be an error condition in future versions of Rails.
How to properly configure a singleton class while using Zeitwerk ?