Skip to content

Instantly share code, notes, and snippets.

@ericboehs
Last active June 7, 2018 19:35
Show Gist options
  • Save ericboehs/3784960cb801318f13f82e3a0ed5bd5b to your computer and use it in GitHub Desktop.
Save ericboehs/3784960cb801318f13f82e3a0ed5bd5b to your computer and use it in GitHub Desktop.
Dotenv in 7 lines of Ruby or Crystal
%w[.env .env.local].each do |file|
File.read_lines(file).each do |line|
next if line.starts_with? '#'
key, value = line.strip.split "=", 2
ENV[key] = value
end if File.exists? file
end
%w[.env .env.local].each do |file|
File.readlines(file).each do |line|
next if line.start_with? "#" # optional
key, value = line.split "=", 2
value = value.chomp
value = value[0..-1] if ['\'', '"'].include? value.chars.first # optional
value = value[1...-1] if ['\'', '"'].include? value.chars.last # optional
value = value.gsub '\n', "\n" # optional
ENV[key] ||= value
end if File.exists? file
end
@ericboehs
Copy link
Author

ericboehs commented Jun 24, 2016

You could strip " and ' and convert \n to actual newlines by putting this after the split line:

value = value[0..-1] if ['\'', '"'].includes? value.chars.first
value = value[1...-1] if ['\'', '"'].includes? value.chars.last
value = value.gsub '\n', "\n"

Edit: Added to Ruby version above.

@ericboehs
Copy link
Author

The dotenv gem is 269 lines of code (counting bin and lib only).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment