Rails custom configuration returns an empty hash

2019-05-11 13:08发布

问题:

I'm using Rails 4, and I would like to use the custom configuration functionality as explained here:

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

I created the following YAML file (config\prefs.yml):

development:
  password: test

And I added this to my config/application.rb:

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

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

When I go to the rails console, I get this:

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

Why isn't Rails correctly loading the configuration?

回答1:

I'm guessing the following:

  • You have the Spring gem bundled in.
  • Your custom configuration somehow got initialized in the state it is currently in. (i.e. empty)
  • The config\prefs.yml isn't tracked by Spring, so it doesn't know the environment needs to be reloaded.

If i'm correct, you'll just have to create an initializer with the following code:

Spring.watch "config/prefs.yml"

And, of course, you'll have to reload the console each time the config is changed. I've managed to reproduce and solve your issue with this, so i hope this helps.



回答2:

I try your code on my machine and working fine i think maybe problem with configuration you did in config/application.rb or you need to reload your rails console with reload command reload!

that my configuration for 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

that your file prefs.yml

development:
  password: test

here is the result