Search code examples
ruby-on-railsruby-on-rails-4

Rails 4 - Yaml configuration file


I have this file config/application.yml

settings:
  info:
    name: MyAppName
    domain: example.com
  contact:
    email: mail@example.com
    phone: 1234567890

And in the environment.rb i have this

AppConfig = YAML::load_file('config/application.yml')

So now i can access this by using AppConfig["settings"]["info"]["name"]

How can i access this by using AppConfig.settings.info.name ?


Solution

  • If you are using Rails 4.2 or higher, you can use config_for for the config files. They need to be placed under /config folder. (haven't tried otherwise)

    In your case it would be: config = Rails.application.config_for(:application)

    This is more clear and Rails way to load configs into application.

    Then you can use OpenStruct to have dot notation enabled for it.

    APP_CONFIG = OpenStruct.new(config)