Rails自定义配置返回空哈希

时间:2016-01-17 18:03:20

标签: ruby-on-rails ruby-on-rails-4 configuration

我正在使用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没有正确加载配置?

2 个答案:

答案 0 :(得分:7)

我在猜测以下内容:

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

如果我没错,您只需要使用以下代码创建初始化程序:

Spring.watch "config/prefs.yml"

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

答案 1 :(得分:0)

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

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

这是结果

enter image description here