I've followed the steps from this video from railscasts for setting ENV
variables.
This is my configuration:
config/database.yml
default: &default
adapter: mysql2
encoding: utf8
pool: 5
username: <%= ENV['DATABASE_USERNAME'] %>
password: <%= ENV['DATABASE_PASSWORD'] %>
socket: /var/run/mysqld/mysqld.sock
development:
<<: *default
database: <%= ENV['DATABASE_NAME'] %>
test:
<<: *default
database: <%= ENV['DATABASE_NAME'] %>
production:
<<: *default
database: <%= ENV['DATABASE_NAME'] %>
username: <%= ENV['DATABASE_USERNAME'] %>
password: <%= ENV['DATABASE_PASSWORD'] %>
config/application.rb
config = YAML.load(File.read(File.expand_path('../application.yml', __FILE__)))
config.merge! config.fetch(Rails.env, {})
config.each do |key, value|
ENV[key] = value.to_s unless value.kind_of? Hash
end
config/application.yml
development:
DATABASE_USERNAME: "username goes here"
DATABASE_PASSWORD: "password goes here"
DATABASE_NAME: "database name goes here"
SECRET_KEY_BASE: "secret key goes here"
test:
DATABASE_USERNAME: "username goes here"
DATABASE_PASSWORD: "password goes here"
DATABASE_NAME: "database name goes here"
SECRET_KEY_BASE: "secret key goes here"
production:
DATABASE_USERNAME: "username goes here"
DATABASE_PASSWORD: "password goes here"
DATABASE_NAME: "database name goes here"
SECRET_KEY_BASE: "secret key goes here"
Does this configuration follow best practices, or need some changes?
2 Answers 2
for what you use config/application.yml
instead use config/secrets.yml
. It is already implemented in Rails. Than you can fetch your key by:
Rails.application.secrets
even more, add to config/application.rb
variable SECRETS = Rails.application.secrets
and now you can use it:
SECRETS[:my_secret_key]
read more IN RAILS DOCS
-
\$\begingroup\$ so, everything I have in
config/application.yml
should move toconfig/secrets.yml
, right? so the ENV variables should be in another .yml file likw I have or in shell ? \$\endgroup\$Lykos– Lykos2016年10月17日 11:49:56 +00:00Commented Oct 17, 2016 at 11:49 -
\$\begingroup\$ yes, move data from
application.yml
tosecret.yml
. ENV variables you need in HEROKU, AWS etc, but for example in DigitalOcean or in local server you can work withsecrets.yml
\$\endgroup\$Oleh Sobchuk– Oleh Sobchuk2016年10月17日 13:36:02 +00:00Commented Oct 17, 2016 at 13:36
An Alternative is ..
Add gem 'config' to your Gemfile and run bundle install to install it. Then run
rails g config:install
which will generate customizable config file config/initializers/config.rb and set of default settings files:
config/settings.yml
config/settings/development.yml
config/settings/production.yml
config/settings/test.yml
You can now edit them to adjust to your needs. a
see the usage in https://github.com/railsconfig/config compatible Rails>= 3.1, 4 and 5
Explore related questions
See similar questions with these tags.
VAR=value rails server
. \$\endgroup\$