Rails 自定义配置 returns 空哈希

Rails custom configuration returns an empty hash

我正在使用 Rails 4,我想使用自定义配置功能,如下所述:

http://guides.rubyonrails.org/configuring.html#custom-configuration

我创建了以下 YAML 文件 (config\prefs.yml):

development:
  password: test

我把这个添加到我的 config/application.rb:

module MyApp
  class Application < Rails::Application
    # ...

    config.x.prefs = Rails.application.config_for(:prefs)
  end
end

当我进入 rails 控制台时,我得到了这个:

> Rails.configuration.x.prefs
=> {}

为什么 Rails 没有正确加载配置?

我猜如下:

  • 您捆绑了 Spring gem。
  • 您的自定义配置以某种方式初始化为当前状态(即空)
  • config\prefs.yml 未被 Spring 跟踪,因此它不知道需要重新加载环境。

如果我是正确的,您只需使用以下代码创建一个初始值设定项:

Spring.watch "config/prefs.yml"

当然,每次更改配置时您都必须重新加载控制台。我已经设法重现并解决了您的问题,所以我希望这对您有所帮助。

我在我的机器上尝试了你的代码并且工作正常我认为你在 config/application.rb 中所做的配置可能有问题或者你需要使用重新加载命令 reload![重新加载你的 rails 控制台

我的 config/application.rb

配置
require File.expand_path('../boot', __FILE__)

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module WSApp
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Central Time (US & Canada)'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de

    # Do not swallow errors in after_commit/after_rollback callbacks.
    config.active_record.raise_in_transactional_callbacks = true
    config.x.prefs = Rails.application.config_for(:prefs)
  end
end

你的文件 prefs.yml

development:
  password: test

这是结果