Skip to content

Instantly share code, notes, and snippets.

@asaaki
Last active November 7, 2019 19:42
Show Gist options
  • Save asaaki/bf238f6ab99be5cb8c5f073c54094d96 to your computer and use it in GitHub Desktop.
Save asaaki/bf238f6ab99be5cb8c5f073c54094d96 to your computer and use it in GitHub Desktop.
Env Vars as Booleans

Boolean Environment Variables

Don't overcomplicate things.

I've seen a lot of parse the env var and match it against some known values like:

env_var = ENV['FEATURE_ONE']
case env_var.to_s.downcase
when 'true', 't', 'yes', 'y', 'on', '1' then true
when 'false', 'f', 'no', 'n', 'off', '0' then false
else raise ArgumentError, 'Invalid input detected'
end

This is unecessarily bloated. It also doesn't help that much.
Use the existence of an env var as a guard if something is on or off.

That means: only set env vars if you need them.
Also: if you know a variable is set and you need to turn it off, simply use unset FEATURE_ONE.
Done.

'use strict';
const isSet = function(envKey) {
return (envKey in process.env);
}
module.exports = {
isSet,
enabled: isSet
}
/*
USAGE:
const { enabled } = require('./boolenv.js');
const featureOneEnabled = enabled('FEATURE_ONE');
console.log('feature one enabled:', featureOneEnabled);
*/
module Boolenv
class << self
def is_set(env_key)
ENV.key?(env_key)
end
alias enabled is_set
end
end
__END__
USAGE:
require('./boolenv.rb')
feature_one_enabled = Boolenv.enabled('FEATURE_ONE')
puts "feature one enabled: #{feature_one_enabled}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment