Dotenv-schema makes dotenv schemaful.
Installation
Write .env
and .env_schema
:
$ cat .env
DB_HOST=db.example.com
DB_PORT=3306
$ cat .env_schema
DB_HOST:
DB_PORT:
Rails
Add this line to your application's Gemfile:
gem 'dotenv-schema-rails'
# DO NOT load dotenv-rails gem! Use dotenv-schema-rails instead.
And then execute:
$ bundle
$ rails server
It raises Dotenv::Schema::ValidationError if the validation failed.
Sinatra or Plain ol' Ruby
$ gem install dotenv
require 'dotenv-schema'
Dotenv.load # raises Dotenv::Schema::ValidationError if the validation failed.
Schema validation rule and .env_schema
format
.env_schema
is written in YAML format.
Basic rule
Validation fails when all variable names that defined in .env_schema
don't exist in .env
.
# .env_schema
DB_HOST:
DB_PORT:
# .env
DB_HOST=db.example.com
# => Dotenv::Schema::ValidationError: ENV['DB_PORT'] must exist
Validation fails if any variables which not defined in .env_schema
are defined in .env
.
# .env_schema
DB_HOST:
# .env
DB_HOST=db.example.com
DB_PORT=3306
# => Dotenv::Schema::ValidationError: Undefined variable(s): DB_PORT; Please add them into .env_schema
To allow empty string
In default, validation fails when any variable in .env
is empty string.
# .env_schema
DB_HOST:
# .env
DB_HOST=
# => Dotenv::Schema::ValidationError: ENV['DB_HOST'] must not be empty string
You can allow it by using allow_empty_string
option.
# .env_schema
DB_HOST:
allow_empty_string: true
# .env
DB_HOST=
# => Passes validation even though DB_HOST is empty
To allow variables to don't exist
# .env_schema
DB_HOST:
DB_PORT:
allow_not_exists: true
# .env
DB_HOST=
# => Passes validation even though DB_PORT doesn't exist