【问题标题】:Rails custom configuration returns an empty hashRails 自定义配置返回一个空哈希
【发布时间】:2016-04-22 20:32:50
【问题描述】:

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

【问题讨论】:

  • 当您运行Rails.env 时,它是否显示"development" 或其他内容?如果由于某种原因您没有在开发环境中运行,那么当它设置首选项哈希时,它将为空。

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


【解决方案1】:

我猜如下:

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

如果我是正确的,您只需使用以下代码创建一个初始化程序:

Spring.watch "config/prefs.yml"

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

【讨论】:

  • reload! 是快速重新加载控制台的好方法
  • 很抱歉这么晚才回来,我正在旅行。这正是我遇到这个问题的原因,你是完全正确的。我将您的线路添加到config/spring.rb,一切正常。顺便说一句,@blnc reload! 命令不起作用。
  • @hattenn 它适用于模型的更新,认为它可能适用于春季
  • @blnc,我也经常使用reload!,但它不适用于春季。我想如果这样做会很方便。
【解决方案2】:

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

我对@9​​87654325@的配置

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

这是结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多