Class: Opdotenv::Parsers::DotenvParser

Inherits:
Object
  • Object
show all
Defined in:
lib/opdotenv/parsers/dotenv_parser.rb

Class Method Summary collapse

Class Method Details

.parse(text) ⇒ Object



4
5
6
7
8
9
10
11
# File 'lib/opdotenv/parsers/dotenv_parser.rb', line 4

def self.parse(text)
  text.to_s.each_line.with_object({}) do |line, env|
    entry = parse_line(line)
    next unless entry

    env[entry[:key]] = entry[:value]
  end
end

.parse_line(line) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/opdotenv/parsers/dotenv_parser.rb', line 13

def self.parse_line(line)
  line = line.strip
  return nil if line.empty? || line.start_with?("#")

  line = line.sub(/^export\s+/, "")
  match = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\z/)
  return nil unless match

  {key: match[1], value: unquote_value(match[2])}
end

.unquote_value(raw) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'lib/opdotenv/parsers/dotenv_parser.rb', line 24

def self.unquote_value(raw)
  if raw.start_with?("\"") && raw.end_with?("\"")
    raw[1..-2].gsub('\\"', '"')
  elsif raw.start_with?("'") && raw.end_with?("'")
    raw[1..-2]
  else
    raw
  end
end