An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
Ensure required environment variables are set when booting up Rails
Its common to use environment variables to configure external services or other options in a Rails app. These ENV_VARS
usually are not checked into source control, but rather configured per environment.
Rails has the concept of initializers
, which is code run during the boot phase of a Rails app.
You can add a custom initializer
to check that required environment variables are set to avoid exceptions later on when your code expects a value to exist.
Usage
Create a new initializer in your app and add the required variables:
# config/initializers/01_ensure_environment.rbif Rails.env.development? %w[ AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY S3_BUCKET ALGOLIA_ID ALGOLIA_API_KEY ALGOLIA_SEARCH_KEY ALGOLIA_INDEX ALGOLIA_CAMPAIGN_INDEX TWITTER_API_SECRET TWITTER_API_TOKEN ].each do |env_var| if !ENV.has_key?(env_var) || ENV[env_var].blank? raise <<~EOL Missing environment variable: #{env_var} Ask a teammate for the appropriate value. EOL end endend
Options
Rails initializers are loaded and executed in alphabetical order. So use a name like 01_ensure_environment.rb
to control the sort order and make sure this one loads first.
You may wish to check in a sample .env.sample
file into git (without any values) to make it easier for new team members to get their environment into a working state.
Additional Resources
Rails Doc: Configuring Rails apps
Original Link: https://dev.to/swanson/ensure-required-environment-variables-are-set-when-booting-up-rails-kal
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To