gpt4 book ai didi

ruby-on-rails - 在环境之前加载初始化程序

转载 作者:行者123 更新时间:2023-12-02 14:44:34 25 4
gpt4 key购买 nike

我有一个 Rails 应用程序,我放置了所有重要的配置,例如sendgrid、new relic、twilio、airbrake 等,位于 config/config.yml 文件中。该文件如下所示:

development:
sendgrid:
username: username
password: password

test:
sendgrid:
username: username
password: password

production:
sendgrid:
username: username
password: password

然后在 config/initializers/global_configuration.rb 中,我加载正确的环境配置:

APP_CONFIG = YAML.load_file("#{Rails.root}/config/config.yml")[Rails.env]

现在我希望能够在 config/environments/development 或 config/environments/Production 中访问这个全局常量,如下所示:

  config.action_mailer.smtp_settings = {
address: 'smtp.sendgrid.net',
port: 587,
domain: APP_CONFIG['sendgrid']['domain'],
authentication: "plain",
enable_starttls_auto: true,
user_name: APP_CONFIG['sendgrid']['username'],
password: APP_CONFIG['sendgrid']['password']
}

不幸的是,当 Rails 启动时,它会抛出以下错误:

Uncaught exception: uninitialized constant APP_CONFIG

看来 config/environments 是在 config/initializers 之前加载的。我怎样才能解决这个问题,以便我可以访问配置/环境中的全局常量?

最佳答案

看来 config/application.rb 在 config/environments/*.rb 文件之前加载,因此我能够挂接到 before_configuration block ,然后在其中创建一个全局变量:

config.before_configuration do
::APP_CONFIG = YAML.load_file("#{Rails.root}/config/config.yml")[Rails.env]
end

如果有更好的选择(而不是使用 ENV),我会很乐意删除此答案并投票给更好的答案。

关于ruby-on-rails - 在环境之前加载初始化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29997958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com