dotenv Ruby Library

repository·main·Indexed 27 days ago

https://github.com/bkeepers/dotenv

A Ruby library that loads environment variables from a .env file into the ENV hash, primarily for development and testing. It includes a CLI for launching scripts with loaded variables, a parser for .env strings, and specialized integration for Rails applications including automatic loading and test state restoration.

Tokens
2.9K
Snippets
9
Records
29
Agent score
92%

What's inside dotenv

  1. Install dotenv via Gemfile

    main

    To use dotenv in your Ruby application, add it to your Gemfile within the :development and :test groups to ensure it doesn't run in production environments unless explicitly required.

    gem 'dotenv', groups: [:development, :test]
  2. Configure Load Order in Gemfile

    main

    If certain gems require environment variables to be present during their own load phase, place dotenv before them in your Gemfile and use the require: 'dotenv/load' option.

    gem 'dotenv', require: 'dotenv/load'
    gem 'gem-that-requires-env-variables'
  3. Configure Autorestore in Tests

    main

    Since version 3.0, dotenv in Rails apps automatically restores the ENV state after each test to prevent state leakage. This works with ActiveSupport::TestCase and Rspec.

    • To disable in Rails: Set config.dotenv.autorestore = false in config/application.rb or config/environments/test.rb.
    • To use in non-Rails apps: Add require "dotenv/autorestore" to your test suite.
  4. Basic Usage for Sinatra or Ruby

    main

    In non-Rails Ruby or Sinatra applications, load dotenv as early as possible in your bootstrap process. By default, Dotenv.load looks for a .env file in the current working directory. You can pass multiple files to load, which will be processed in order; the first value set for a variable wins. Existing environment variables are not overwritten by default.

    require 'dotenv/load'
    
    # or
    require 'dotenv'
    Dotenv.load
    
    # To load multiple files in order:
    Dotenv.load('file1.env', 'file2.env')
  5. Customize Rails dotenv loading

    main

    Dotenv loads files during the before_configuration callback in Rails. You can customize the loading process by modifying Dotenv::Rails.files or other options in config/application.rb.

    Available Options:

    • Dotenv::Rails.files: List of files to be loaded (in order of precedence).
    • Dotenv::Rails.overwrite: Boolean to overwrite existing ENV variables.
    • Dotenv::Rails.logger: The logger to use (defaults to Rails.logger).
    • Dotenv::Rails.autorestore: Enable/disable test autorestore.
    # config/application.rb
    Bundler.require(*Rails.groups)
    
    # Example: Manually unshifting a file to increase precedence
    Dotenv::Rails.files.unshift(".env.local") if ENV["RAILS_ENV"] == "test"
    
    module YourApp
      class Application < Rails::Application
        # ...
      end
    end
  6. Use dotenv in Rake tasks

    main

    To ensure environment variables from .env are available within a Rake task, require dotenv/tasks and make your task depend on the :dotenv task.

    require 'dotenv/tasks'
    
    task mytask: :dotenv do
      # things that require .env
    end
  7. Parse .env files without modifying ENV

    main

    Use Dotenv.parse to inspect the contents of one or more .env files as a hash without actually loading them into the global ENV object.

    Dotenv.parse(".env.local", ".env")
    # => {'S3_BUCKET' => 'YOURS3BUCKET', 'SECRET_KEY' => 'YOURSECRETKEYGOESHERE', ...}
  8. Require specific environment keys

    main

    To prevent the application from starting if essential configuration is missing, use Dotenv.require_keys. This raises an error during initialization if any specified keys are not found in ENV.

    # config/initializers/dotenv.rb
    Dotenv.require_keys("SERVICE_APP_ID", "SERVICE_KEY", "SERVICE_SECRET")
  9. Control newline expansion with DOTENV_LINEBREAK_MODE

    main

    The parser handles newline characters (\n and \r) in double-quoted values based on the DOTENV_LINEBREAK_MODE setting. This can be set via the @hash (internal to the parser) or as an environment variable ENV['DOTENV_LINEBREAK_MODE'].

    • legacy: Converts \n to actual newlines (\n) and \r to actual carriage returns (\r).
    • Default (not legacy): Escapes newlines to literal strings (\\\\n and \\\\r).
  10. Configure Dotenv for Rails

    main

    When using dotenv-rails, you can configure how environment variables are loaded via config.dotenv. The following configuration keys are available through delegation:

    • files: An array of file patterns to load.
    • overwrite: Boolean indicating whether to overwrite existing environment variables.
    • autorestore: Boolean to enable automatic restoration of environment variables (primarily used in tests).
    • logger: The logger instance used by dotenv.

    By default, dotenv-rails loads files in this order (based on the current environment):

    1. .env.{env}.local
    2. .env.local (unless in the test environment)
    3. .env.{env}
    4. .env
  11. Format .env file values

    main

    Multi-line values

    Wrap multi-line values in double quotes:

    PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
    ...
    -----END RSA PRIVATE KEY-----"

    Note: To use legacy \n replacement, set DOTENV_LINEBREAK_MODE=legacy.

    Command Substitution

    Use $(command) to include command output:

    DATABASE_URL="postgres://$(whoami)@localhost/my_database"

    Variable Substitution

    Reference other variables using ${VAR} or $VAR:

    DATABASE_URL="postgres://${USER}@localhost/my_database"

    If a value contains a $ that should not be treated as a variable, wrap it in single quotes: PASSWORD='pas$word'.

    Comments

    Use # for comments:

    # This is a comment
    SECRET_KEY=VALUE # comment