Last active
June 7, 2018 19:35
-
-
Save ericboehs/3784960cb801318f13f82e3a0ed5bd5b to your computer and use it in GitHub Desktop.
Dotenv in 7 lines of Ruby or Crystal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%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 |
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
You could strip
"
and'
and convert\n
to actual newlines by putting this after thesplit
line:Edit: Added to Ruby version above.