philiprehberger-env_loader

Tests Gem Version Last updated

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]
)

Parse from a String

Parse .env-formatted text without reading from disk and without touching ENV:

content = <<~ENV
  APP_HOST=localhost
  APP_PORT=3000
  # comments and blank lines are ignored
ENV

Philiprehberger::EnvLoader.parse(content)
# => { "APP_HOST" => "localhost", "APP_PORT" => "3000" }

Dump to .env Format

Serialize a hash back to .env-formatted text. Round-trips with parse for any input. Values that contain whitespace, =, #, or quote characters are double-quoted with inner " and \ backslash-escaped. Keys are sorted alphabetically.

text = Philiprehberger::EnvLoader.dump(
  'APP_HOST' => 'localhost',
  'APP_PORT' => '3000',
  'NOTE' => 'has "quote"'
)
# => "APP_HOST=localhost\nAPP_PORT=3000\nNOTE=\"has \\\"quote\\\"\"\n"

File.write('.env', text)

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
.parse(content) Parse .env-formatted content from a string into a hash without touching ENV
.dump(hash) Serialize a hash to .env-formatted text (round-trips with parse)
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:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT