Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 17, 2021 01:00 pm GMT

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
Enter fullscreen mode Exit fullscreen mode

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

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To