■Japanese Version↓
[RubyOnRailsで環境変数を使用する方法]
(https://qiita.com/alokrawat050/items/c68ec9578c12fe5a93a3)
Environment Variables
Every applications require a configuration settings such as email account credentials or API keys for external services(security purpose). You can pass local configuration settings to an application using environment variables.
There are several methods to use the environment variables in Ruby On Rails and also we have a gem like a Figaro Gem.
Keep Your Environment Variables File As a Private
If you are using the GitHub, to store and share code and your project is open source,it means any developer will have access to your code. You don’t want to share your private details or API keys with the public. If you are collaborating on a team with a private git repository, your local settings may not be suitable for all members of the team.
Using a local_env.yml File:
We will create a simple file that contains key/value pairs for each environment variable using the standard YAML file format.
Create a file config/local_env.yml:
'# makes 'Your_Gmail_Username' available as ENV["GMAIL_USERNAME"]
MAIL_USERNAME: 'Your_Username'
MAIL_PASSWORD: 'Your_Password'
Setting in .gitignore
If you have created a git repository for your application, your application root directory should contain a file named .gitignore.
add below line in your .gitignore file.
/config/local_env.yml
This prevents the config/local_env.yml file from being checked into a git repository and made available for others to see.
Rails Application Configuration File
After setting env variables,we have to set local_env.yml file into config/application.rb file.
in the config/application.rb file:
add the below code:
config.before_configuration do
env_file = File.join(Rails.root, 'config', 'local_env.yml')
YAML.load(File.open(env_file)).each do |key, value|
ENV[key.to_s] = value
end if File.exists?(env_file)
end
The above code sets environment variables from local_env.yml file.
Use environment variables in your code
Use ENV["MAIL_USERNAME"] anywhere in a Rails application.
for example,
ActionMailer::Base.smtp_settings = {
address: "smtp.gmail.com",
enable_starttls_auto: true,
port: 587,
authentication: :plain,
user_name: ENV["MAIL_USERNAME"],
password: ENV["MAIL_PASSWORD"],
openssl_verify_mode: 'none'
}
Enjoy Coding.
Thanks & Best Regards,
Alok Rawat