■ Articles in English ↓ [How to Use Environment Variables in Ruby On Rails] (https://qiita.com/alokrawat050/items/ff6dceec32baa0c8fa57)
Each application requires configuration settings such as email account credentials and API keys for external services. You can use environment variables to pass local configuration settings to your application. There are several ways to use environment variables in Ruby On Rails, and there are also gems like FigaroGem. For this article, I'll use the local_env.yml file to share how to implement it.
If you're using GitHub to store and share your code and your project is open source, any developer can access your code. If you're collaborating with your team using a private git repository that you don't want to share your personal information or API keys with the public, local settings may not be suitable for all members of your team.
Use the standard YAML file format to create a simple file that contains the key / value pairs for each environment variable.
** Create config / local_env.yml file: **
MAIL_USERNAME: 'Your_Username'
MAIL_PASSWORD: 'Your_Username'
** Set to .gitignore ** If you created your application's git repository, your application's root directory should contain a file named .gitignore. Add the following line to the .gitignore file
/config/local_env.yml
** Set in Rails application file ** After setting the environment variables, the file "local_env.yml" needs to be set in "config / application.rb". Set the following code in the ** config / application.rb ** file
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 the local_env.yml file.
** Use environment variables in code ** You can use ENV ["MAIL_USERNAME"] in your Rails application. 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! : grinning:: grinning:
If you have any questions, please contact us.
that's all. Thank you.
Recommended Posts