dotenv.rb 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. require "dotenv/parser"
  2. require "dotenv/environment"
  3. # The top level Dotenv module. The entrypoint for the application logic.
  4. module Dotenv
  5. class << self
  6. attr_accessor :instrumenter
  7. end
  8. module_function
  9. def load(*filenames)
  10. with(*filenames) do |f|
  11. ignoring_nonexistent_files do
  12. env = Environment.new(f)
  13. instrument("dotenv.load", :env => env) { env.apply }
  14. end
  15. end
  16. end
  17. # same as `load`, but raises Errno::ENOENT if any files don't exist
  18. def load!(*filenames)
  19. with(*filenames) do |f|
  20. env = Environment.new(f)
  21. instrument("dotenv.load", :env => env) { env.apply }
  22. end
  23. end
  24. # same as `load`, but will override existing values in `ENV`
  25. def overload(*filenames)
  26. with(*filenames) do |f|
  27. ignoring_nonexistent_files do
  28. env = Environment.new(f)
  29. instrument("dotenv.overload", :env => env) { env.apply! }
  30. end
  31. end
  32. end
  33. # Internal: Helper to expand list of filenames.
  34. #
  35. # Returns a hash of all the loaded environment variables.
  36. def with(*filenames, &block)
  37. filenames << ".env" if filenames.empty?
  38. filenames.reduce({}) do |hash, filename|
  39. hash.merge! block.call(File.expand_path(filename)) || {}
  40. end
  41. end
  42. def instrument(name, payload = {}, &block)
  43. if instrumenter
  44. instrumenter.instrument(name, payload, &block)
  45. else
  46. block.call
  47. end
  48. end
  49. def ignoring_nonexistent_files
  50. yield
  51. rescue Errno::ENOENT
  52. end
  53. end