variable.rb 768B

1234567891011121314151617181920212223242526272829303132333435
  1. require "English"
  2. module Dotenv
  3. module Substitutions
  4. # Substitute variables in a value.
  5. #
  6. # HOST=example.com
  7. # URL="https://$HOST"
  8. #
  9. module Variable
  10. class << self
  11. VARIABLE = /
  12. (\\)? # is it escaped with a backslash?
  13. (\$) # literal $
  14. \{? # allow brace wrapping
  15. ([A-Z0-9_]+) # match the variable
  16. \}? # closing brace
  17. /xi
  18. def call(value, env)
  19. value.gsub(VARIABLE) do |variable|
  20. match = $LAST_MATCH_INFO
  21. if match[1] == '\\'
  22. variable[1..-1]
  23. else
  24. env.fetch(match[3]) { ENV[match[3]] }
  25. end
  26. end
  27. end
  28. end
  29. end
  30. end
  31. end