philiprehberger-env_loader
Multi-source environment variable loader with precedence and validation
Requirements
- Ruby >= 3.1
Installation
Add to your Gemfile:
gem "philiprehberger-env_loader"
Or install directly:
gem install philiprehberger-env_loader
Usage
require "philiprehberger/env_loader"
Philiprehberger::EnvLoader.load('.env', '.env.local',
required: %w[DATABASE_URL SECRET_KEY],
defaults: { 'PORT' => '3000' },
types: { 'PORT' => :integer, 'DEBUG' => :boolean }
)
File Precedence
# Later files override earlier ones; existing ENV always wins
Philiprehberger::EnvLoader.load('.env', '.env.local', '.env.production')
Validation
Philiprehberger::EnvLoader.validate!('DATABASE_URL', 'REDIS_URL')
# raises EnvLoader::ValidationError if any key is missing or empty
Prefix Filtering
require "philiprehberger/env_loader"
# Only load APP_* variables
vars = Philiprehberger::EnvLoader.load(".env", prefix: "APP_")
vars["APP_HOST"] # => "localhost"
# Strip the prefix from keys
vars = Philiprehberger::EnvLoader.load(".env", prefix: "APP_", strip_prefix: true)
vars["HOST"] # => "localhost"
Template Generation
Philiprehberger::EnvLoader.generate_template(
output: '.env.template',
keys: %w[DATABASE_URL REDIS_URL SECRET_KEY PORT]
)
API
| Method | Description |
|---|---|
.load(*files, required:, types:, defaults:, prefix:, strip_prefix:) |
Load variables from .env files with options |
.validate!(*keys) |
Raise if any keys are missing or empty in ENV |
.generate_template(output:, keys:) |
Generate a .env.template file |
EnvLoader::Error |
Base error class for all gem errors |
EnvLoader::ValidationError |
Raised when required keys are missing or empty |
Development
bundle install
bundle exec rspec
bundle exec rubocop
Support
If you find this project useful: