variable.rb 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. (?!\() # shouldnt be followed by paranthesis
  15. \{? # allow brace wrapping
  16. ([A-Z0-9_]+)? # optional alpha nums
  17. \}? # closing brace
  18. /xi
  19. def call(value, env, overwrite: false)
  20. combined_env = overwrite ? ENV.to_h.merge(env) : env.merge(ENV)
  21. value.gsub(VARIABLE) do |variable|
  22. match = $LAST_MATCH_INFO
  23. substitute(match, variable, combined_env)
  24. end
  25. end
  26. private
  27. def substitute(match, variable, env)
  28. if match[1] == "\\"
  29. variable[1..]
  30. elsif match[3]
  31. env.fetch(match[3], "")
  32. else
  33. variable
  34. end
  35. end
  36. end
  37. end
  38. end
  39. end