activerecord-session_store icon indicating copy to clipboard operation
activerecord-session_store copied to clipboard

Deprecation warning when using Zeitwerk and loading custom session class in initializer

Open jerryjohnjacob opened this issue 5 years ago • 2 comments

I have a use case which requires a custom ActiveRecord session class implementation, and I provide that configuration as specified here:

ActionDispatch::Session::ActiveRecordStore.session_class = MySessionClass

I think an ideal location to put this line is a Rails initializer. However, since Zeitwerk comes enabled with Rails 6 by default, new apps have started throwing a deprecation warning:

DEPRECATION WARNING: Initialization autoloaded the constant MySessionClass.

Being able to do this is deprecated. Autoloading during initialization is going
to be an error condition in future versions of Rails.

Reloading does not reboot the application, and therefore code executed during
initialization does not run again. So, if you reload MySessionClass, for example,
the expected changes won't be reflected in that stale Class object.

These autoloaded constants have been unloaded.

It seems just writing this line in an initializer is going to raise an error in a future version of Rails. Please advise on the best method to resolve this.

jerryjohnjacob avatar Oct 16 '20 06:10 jerryjohnjacob

I think we can leverage the to_prepare initialization hook to set the session_class after the Rails autoloader has kicked in. For example

# config/initializers/session_store.rb
Rails.application.config.session_store :active_record_store, key: "_my_app_session"

Rails.application.config.to_prepare do
  ActionDispatch::Session::ActiveRecordStore.session_class = MySessionClass
end

The code in the to_prepare block will run (at least) once for each request as part of re-loading the autoloaded constants (e.g., MySessionClass in this case). But based on both inspecting the code and my own experience using this technique, it's fine to set the session_class on each request.

stevenharman avatar Apr 29 '22 02:04 stevenharman

@stevenharman your suggestion worked for me.

joshRpowell avatar Dec 06 '22 23:12 joshRpowell