Module: Dotenv::Substitutions::Variable

Defined in:
lib/dotenv/substitutions/variable.rb

Overview

Substitute variables in a value.

HOST=example.com
URL="https://$HOST"

Constant Summary collapse

VARIABLE =
/
  (\\)?          # is it escaped with a backslash?
  (\$)           # literal $
  (              # collect braces with var for sub
    \{?          # allow brace wrapping
    ([A-Z0-9_]+) # match the variable
    \}?          # closing brace
  )
/xi

Class Method Summary collapse

Class Method Details

.call(value, env) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/dotenv/substitutions/variable.rb', line 20

def call(value, env)
  # Process embedded variables
  value.scan(VARIABLE).each do |parts|
    if parts.first == '\\'
      # Variable is escaped, don't replace it.
      replace = parts[1...-1].join("")
    else
      # Replace it with the value from the environment
      replace = env.fetch(parts.last) { ENV[parts.last] }
    end

    value = value.sub(parts[0...-1].join(""), replace || "")
  end

  value
end