These days, I use environment variables for credentials and other sensitive data
(secrets.yml
could do the job but is too boilerplate-y for my taste).
Dummy environment values are stored in my project
dotenv file
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 object
that can be accessed with Rails.configuration.x
, and
Rails.application.config_for
loads 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.yml
file in theconfig
directory. It would look something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
- Add this line in your
config/application.rb
file:
1 2 3 4 5 6 7 8 9 10 |
|
You can see that I wrap the loaded configuration hash in a
hashie Mash object.
I just use it for convenience so that I can access configuration variables with dots rather than brackets
(it’s like OpenStruct
with nested hash support).
To use it, add gem 'hashie'
to your Gemfile
.
- You can now access your configuration variables anywhere in your app like so:
1
|
|
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!