Dynamically reloading rails_admin model concerns in development

Syntaf
1 min readAug 8, 2020

--

Here’s the scenario:

  • You’re using the rails_admin gem in your Rails ~6 project
  • You’re configuring your models for rails_admin via concerns, or placing your configuration directly on the model.
  • You don’t want to have to restart your server every time you make a change to your model config (or general rails_admin config)

To give an example of the second point, here’s an example model group.rb and it’s related admin concern concerns/moderate/group_config.rb

This configuration works as intended, however any subsequent changes to GroupConfig will require the server to be restarted. If you’re working with Docker & VSCode this is an absolute pain, not to mention how larger projects can result in slower boot times in general.

The fix? Some rails magic at the ApplicationController level

Step One: Configure a Parent Controller

This can technically be done using the default parent controller, but for simplicity & readability I recommend using the ApplicationController :

Step Two: Define a Reload Mechanism

In order to dynamically reload configurations, we need to call a method on each request that routes to the rails_admin controller:

Step Three: Define the Reload Method

Because we have configuration within our models, we can’t just reload the initialize alone. To work around this we remove the model definition first and load the model definition again.

Done, Done

That’s it! Each time you reload your application, Rails will now reload your rails_admin configurations if the requested route is directed to the rails_admin controller.

Here’s a gist if you’d like to see the final state of the ApplicationController in this example:

--

--