ruby 39 lines · 8 steps

Parsing a .env file in Ruby

A small Dotenv module reads key=value lines, unquotes values, and loads them into ENV without clobbering existing variables.

Explained by highlit
1module Dotenv
2 LINE = /\A\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*\z/
3 
4 module_function
5 
6 def load(path = ".env", overwrite: false)
7 File.foreach(path, chomp: true).each_with_object({}) do |line, parsed|
8 next if line.strip.empty? || line.strip.start_with?("#")
9 
10 match = line.match(LINE) or next
11 key, raw = match.captures
12 value = unquote(raw)
13 
14 parsed[key] = value
15 ENV[key] = value if overwrite || !ENV.key?(key)
16 end
17 end
18 
19 def unquote(raw)
20 case raw
21 when /\A"(.*)"\z/m
22 unescape(Regexp.last_match(1))
23 when /\A'(.*)'\z/m
24 Regexp.last_match(1)
25 else
26 strip_inline_comment(raw)
27 end
28 end
29 
30 def unescape(value)
31 value.gsub(/\\([nrt\\"])/) do
32 { "n" => "\n", "r" => "\r", "t" => "\t", "\\" => "\\", '"' => '"' }.fetch($1)
33 end
34 end
35 
36 def strip_inline_comment(value)
37 value.sub(/\s+#.*\z/, "").strip
38 end
39end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A single anchored regex with capture groups cleanly splits structured text into named parts.
  2. 2Handling quoted, single-quoted, and bare values separately lets you apply the right escaping rules to each.
  3. 3Guarding writes with overwrite || !ENV.key?(key) keeps existing environment values authoritative by default.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing a .env file in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code