railsadminteam / rails_admin

RailsAdmin is a Rails engine that provides an easy-to-use interface for managing your data
MIT License
7.88k stars 2.25k forks source link

Load constants lazily on RailsAdmin initialization #3541

Closed mshibuya closed 2 years ago

mshibuya commented 2 years ago

This is a counter-proposal for #3492, and aims to fix issues #3490, #3501, #3533, and #3534.

My apologies for those issues. This is because of the complexity in RailsAdmin (and Rails) initialization process, which is hard to get it right. Let me explain the story...

RailsAdmin initializer (config/initializers/rails_admin.rb) is loaded during the Rails app's startup process. But as for the actual configuration (= execution of the DSL itself, the code passed in the RailsAdmin.config do |config| ... end block), there're many constraints that all need to be fulfilled for a successful initialization.

So the attempt to address this was made in e4ae669. The idea was basically to delay the execution of the configuration block, after model classes are ready to be autoloaded. But it brought different problems:

Thus, it's like 2 contradicting forces pulling the initialization timing both forward ant backward. That's why I have been struggling in solving this issue without success...

We need a new way to overcome this problem, and here I have come up with one. That is to intercept const_missing to eliminate the necessity for loading actual classes, while delaying the model initialization by utilizing LazyModel, which is the proven method from pre RailsAdmin 3.x era. At the first sight overriding Object.const_missing seemed to have side effects, but from what I tested it looks working well. So I want you guys to try this in your setup, and give feedback on whether this is good idea or not.

Thank you for reading this through, and hoping to hearing back!

@codealchemy @jdufresne @q3aiml (or anyone who is interested in this)

coveralls commented 2 years ago

Coverage Status

Coverage remained the same at 89.498% when pulling 27002eb3e2d4e24e14f743e90f755a5541bd1e83 on load-constants-lazily into 0ebbd857912da9bd76b99ee35fb3d9b95ab78b30 on master.

mshibuya commented 2 years ago

Merged. Thank you for reviewing!

q3aiml commented 2 years ago

This is working well in my testing and resolves https://github.com/railsadminteam/rails_admin/issues/3490. Thank you for figuring this out!