Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jerryjohnjacob opened this issue Oct 16, 2020 · 2 comments

Comments

@jerryjohnjacob
Copy link

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.

@stevenharman
Copy link

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.

@joshRpowell
Copy link

@stevenharman your suggestion worked for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants