Class: Dotenv::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/dotenv/parser.rb

Overview

Parses the ‘.env` file format into key/value pairs. It allows for variable substitutions, command substitutions, and exporting of variables.

Constant Summary collapse

LINE =
/
  (?:^|\A)              # beginning of line
  \s*                   # leading whitespace
  (?:export\s+)?        # optional export
  ([\w.]+)              # key
  (?:\s*=\s*?|:\s+?)    # separator
  (                     # optional value begin
    \s*'(?:\\'|[^'])*'  #   single quoted value
    |                   #   or
    \s*"(?:\\"|[^"])*"  #   double quoted value
    |                   #   or
    [^\#\r\n]+          #   unquoted value
  )?                    # value end
  \s*                   # trailing whitespace
  (?:\#.*)?             # optional comment
  (?:$|\z)              # end of line
/x

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string, overwrite: false) ⇒ Parser

Returns a new instance of Parser.



40
41
42
43
44
# File 'lib/dotenv/parser.rb', line 40

def initialize(string, overwrite: false)
  @string = string
  @hash = {}
  @overwrite = overwrite
end

Class Attribute Details

.substitutionsObject (readonly)

Returns the value of attribute substitutions.



33
34
35
# File 'lib/dotenv/parser.rb', line 33

def substitutions
  @substitutions
end

Class Method Details

.callObject



35
36
37
# File 'lib/dotenv/parser.rb', line 35

def call(...)
  new(...).call
end

Instance Method Details

#callObject



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/dotenv/parser.rb', line 46

def call
  # Convert line breaks to same format
  lines = @string.gsub(/\r\n?/, "\n")
  # Process matches
  lines.scan(LINE).each do |key, value|
    @hash[key] = parse_value(value || "")
  end
  # Process non-matches
  lines.gsub(LINE, "").split(/[\n\r]+/).each do |line|
    parse_line(line)
  end
  @hash
end