Class: Dotenv::Parser

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

Overview

This class enables parsing of a string for key value pairs to be returned and stored in the Environment. It allows for variable 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
    '(?:\\'|[^'])*'  #   single quoted value
    |                #   or
    "(?:\\"|[^"])*"  #   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, is_load = false) ⇒ Parser

Returns a new instance of Parser.



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

def initialize(string, is_load = false)
  @string = string
  @hash = {}
  @is_load = is_load
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

.call(string, is_load = false) ⇒ Object



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

def call(string, is_load = false)
  new(string, is_load).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