Home > Software design >  Upgrading Rails, how to autoload constants before config/environment/devlopment.rb runs?
Upgrading Rails, how to autoload constants before config/environment/devlopment.rb runs?

Time:01-17

I'm new to Ruby and Rails, so please forgive me if this is a n00b question. I'm trying to upgrade a very old app (using Ruby 2.3.4 and Rails 5.0.6) to the latest versions of Ruby (3.1.3) and Rails (7.0.4). When config/environment/devlopment.rb executes, I get an uninitialized constant error. It's trying to access a constant that's defined in a file /lib/settings.rb. If I try to use this constant in a controller, I have no problems. However, trying to use this constant in my development.rb causes the error.

I've already added these lines to my application.rb, but it hasn't helped:

config.autoload_paths << "#{Rails.root}/lib"
config.eager_load_paths << "#{Rails.root}/lib"

From my research, this seems to be a problem with autoloading, and that the new Rails uses something called Zeitwerk which does loading a bit differently. However, I'm not sure how to make this work. Is there a way to get this constant to load before development.rb executes?

CodePudding user response:

Files in lib are not supposed to be autoloaded. Please don't add those configuration lines, instead, issue a

require 'settings'

in config/environments/development.rb.

CodePudding user response:

The reason for the error is likely caused by changes in how Rails handles autoloading in the latest versions. In previous versions of Rails, constants defined in lib were automatically loaded, but in newer versions this is not the case.

One solution is to use the require_dependency method in your development.rb file to explicitly require the file that defines the constant. For example:

require_dependency "#{Rails.root}/lib/settings"

Alternatively, you can use the config.autoload_paths and config.eager_load_paths settings in your application.rb file to specify that Rails should automatically load files in the lib directory. However, based on your existing configuration this should be already covered.

Another option is to move the constant definition to a file located under the app directory, which will be automatically loaded by Rails.

It's also worth noting that upgrading such a large version gap of Ruby and Rails may require significant effort and testing, and it's recommended to take a backup of the current application before proceeding with the upgrade.

  • Related