class Dotenv::Parser

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.

Constants

LINE

Attributes

substitutions[R]

Public Class Methods

call(string, is_load = false) click to toggle source
# File lib/dotenv/parser.rb, line 35
def call(string, is_load = false)
  new(string, is_load).call
end
new(string, is_load = false) click to toggle source
# File lib/dotenv/parser.rb, line 40
def initialize(string, is_load = false)
  @string = string
  @hash = {}
  @is_load = is_load
end

Public Instance Methods

call() click to toggle source
# 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

Private Instance Methods

expand_newlines(value) click to toggle source
# File lib/dotenv/parser.rb, line 90
def expand_newlines(value)
  value.gsub('\n', "\n").gsub('\r', "\r")
end
parse_line(line) click to toggle source
# File lib/dotenv/parser.rb, line 62
def parse_line(line)
  if line.split.first == "export"
    if variable_not_set?(line)
      raise FormatError, "Line #{line.inspect} has an unset variable"
    end
  end
end
parse_value(value) click to toggle source
# File lib/dotenv/parser.rb, line 70
def parse_value(value)
  # Remove surrounding quotes
  value = value.strip.sub(/\A(['"])(.*)\1\z/m, '\2')

  if Regexp.last_match(1) == '"'
    value = unescape_characters(expand_newlines(value))
  end

  if Regexp.last_match(1) != "'"
    self.class.substitutions.each do |proc|
      value = proc.call(value, @hash, @is_load)
    end
  end
  value
end
unescape_characters(value) click to toggle source
# File lib/dotenv/parser.rb, line 86
def unescape_characters(value)
  value.gsub(/\\([^$])/, '\1')
end
variable_not_set?(line) click to toggle source
# File lib/dotenv/parser.rb, line 94
def variable_not_set?(line)
  !line.split[1..-1].all? { |var| @hash.member?(var) }
end