After migration Rails 6.0.34 -> 6.1 I can't use model inside the config/environments/development.rb

Viewed 288

I have Rails 6.1.0 app:

config.action_mailer.smtp_settings[:password] = AppConfig::Mailchimp.api_key

config/environments/development.rb

module AppConfig
  class Mailchimp
    def self.api_key
     
      key = ENV['MAILCHIMP_API']
      # some additional processing here
      # ...
      key
    end
  end
end

app/models/app_config/mailchimp.rb

when trying to run dev console getting:

/config/environments/development.rb:59:in `block in <top (required)>': uninitialized constant AppConfig (NameError)

I'm after migration 6.0.3.4 -> 6.1 and it worked fine for the older Rails version. Apparently they have changed way of loading things in new version, but I'm wondering:

  1. Does anyone know the rationale of that change, any specific reason which brought Rails team to change that or it was not intentional.

  2. How to fix it, I have at least 2 options:

2 Answers

Use an initializer for setting up the mailer settings after the environment is loaded:

# config/initializers/custom_smtp.rb

ActionMailer::Base.smtp_settings.merge!({ password: AppConfig::Mailchimp.api_key })

Rails introduced the new Zeitwerk autoloader and has been inching its' way into full adoption with Rails 6. If you scan down to the bottom of the Rails Configuration Guide, you'll see there are two options available to you if you desire to keep the old way things worked:

config.load_defaults 6.0
config.autoloader = :classic

With those in place, your original code should continue to work. However, from the example you gave, I urge you to consider using Rails credentials. To do that, first run:

bin/rails credentials:edit

Add an entry for your Mailchimp API key:

mailchimp_api_key: abc1234

When you need to reference it, you just do:

config.action_mailer.smtp_settings[:password] = Rails.application.credentials.mailchimp_api_key
Related