Leveraging Rails' custom configuration

来源:互联网 时间:1970-01-01

These days, I use environment variables for credentials and other sensitive data ( secrets.ymlcould do the job but is too boilerplate-y for my taste). Dummy environment values are stored in my project dotenvfile and production values are deployed to the PaaS server of my choice with a simple heroku config:set/ eb setenv/ etc.

But what about non-sensitive configuration values such as emails or your company address?

Storing them in environment variables both in your project and in your server is overkill and not really compliant with 12 factor apps. Those values are best stored in your project source code, in some sort of configuration file.

Rails 4.2 introduced a custom configuration objectthat can be accessed with Rails.configuration.x, and Rails.application.config_forloads YAML file values depending on the environment. By combining those two features, you can have all your custom configuration in a handy all-in-one YAML file!

Say your project is called MyApp:

Create a my_app.ymlfile in the configdirectory. It would look something like this: # MyApp custom configuration.# Do not put sensitive data in this file (use environment variables instead).default: &default emails: support: [email protected] marketing: [email protected] company_address: 221B Baker Streetproduction: <<: *defaultdevelopment: <<: *default emails: support: [email protected]: <<: *default Add this line in your config/application.rbfile: # ...module MyApp class Application < Rails::Application # ... # Custom configuration config.x = Hashie::Mash.new(Rails.application.config_for(:my_app)) endend

You can see that I wrap the loaded configuration in a hashie Mashobject. You don’t have to, I just use it for convenience so that I can access configuration variables with dots rather than brackets. If you want to use it, add gem 'hashie'to your Gemfile.

You can now access your configuration variables anywhere in your app like so: Rails.configuration.x.company_address

If you did not want to use hashie, you would do:


I hope that in future releases, Rails will improve its secret and configuration handling so that they can be even easier to use out of the box. But for now, this will do!