Module: Philiprehberger::EnvLoader
- Defined in:
- lib/philiprehberger/env_loader.rb,
lib/philiprehberger/env_loader/version.rb
Defined Under Namespace
Classes: Error, ValidationError
Constant Summary collapse
- VERSION =
'0.4.0'
Class Method Summary collapse
-
.dump(hash) ⇒ String
Serialize a hash to ‘.env`-formatted text suitable for writing to a file or passing to EnvLoader.parse.
-
.generate_template(output:, keys: []) ⇒ void
Generate a .env.template file listing all currently loaded keys.
-
.load(*files, required: [], types: {}, defaults: {}, prefix: nil, strip_prefix: false) ⇒ Hash<String, String>
Load environment variables from one or more .env files with options.
-
.parse(content) ⇒ Hash{String => String}
Parse ‘.env`-formatted content from a string into a hash.
-
.validate!(*keys) ⇒ void
Validate that all specified keys are present and non-empty in ENV.
Class Method Details
.dump(hash) ⇒ String
Serialize a hash to ‘.env`-formatted text suitable for writing to a file or passing to parse.
Keys are emitted in alphabetical order. Values that contain whitespace, ‘=`, `#`, or quote characters are wrapped in double quotes with inner `“` and `` backslash-escaped. `nil` values become empty (`KEY=`). The output always ends with a single trailing newline.
124 125 126 127 128 129 130 |
# File 'lib/philiprehberger/env_loader.rb', line 124 def self.dump(hash) lines = hash.to_h .transform_keys(&:to_s) .sort_by(&:first) .map { |key, value| "#{key}=#{format_value(value)}" } "#{lines.join("\n")}\n" end |
.generate_template(output:, keys: []) ⇒ void
This method returns an undefined value.
Generate a .env.template file listing all currently loaded keys.
62 63 64 65 66 |
# File 'lib/philiprehberger/env_loader.rb', line 62 def self.generate_template(output:, keys: []) target_keys = keys.empty? ? ENV.keys.sort : keys.map(&:to_s).sort content = target_keys.map { |key| "#{key}=" }.join("\n") File.write(output, "#{content}\n") end |
.load(*files, required: [], types: {}, defaults: {}, prefix: nil, strip_prefix: false) ⇒ Hash<String, String>
Load environment variables from one or more .env files with options.
Files are loaded in order; later files take precedence. Existing ENV values take precedence over all files unless overridden.
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/philiprehberger/env_loader.rb', line 21 def self.load(*files, required: [], types: {}, defaults: {}, prefix: nil, strip_prefix: false) loaded = {} defaults.each { |key, value| loaded[key.to_s] = value.to_s } files.each do |file| next unless File.exist?(file) parse_file(file).each { |key, value| loaded[key] = value } end loaded.each { |key, value| ENV[key] = value unless ENV.key?(key) } missing = required.map(&:to_s).select { |key| ENV[key].nil? || ENV[key].empty? } raise ValidationError, "missing required keys: #{missing.join(', ')}" unless missing.empty? coerce_types(types) if prefix loaded = loaded.select { |key, _| key.start_with?(prefix) } loaded = loaded.transform_keys { |key| key.delete_prefix(prefix) } if strip_prefix end loaded end |
.parse(content) ⇒ Hash{String => String}
Parse ‘.env`-formatted content from a string into a hash.
Useful for tests, embedded configurations, and any scenario where the ‘.env` content does not live in a file. Comments (`#`), blank lines, and surrounding whitespace are ignored. Single- and double-quoted values are unwrapped. ENV is not touched.
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/philiprehberger/env_loader.rb', line 77 def self.parse(content) result = {} content.to_s.each_line do |line| line = line.strip next if line.empty? || line.start_with?('#') key, value = line.split('=', 2) next if key.nil? || value.nil? key = key.strip value = value.strip if value.length >= 2 && value.start_with?('"') && value.end_with?('"') value = value[1..-2].gsub(/\\(.)/) { Regexp.last_match(1) == 'n' ? "\n" : Regexp.last_match(1) } elsif value.length >= 2 && value.start_with?("'") && value.end_with?("'") value = value[1..-2] end result[key] = value end result end |
.validate!(*keys) ⇒ void
This method returns an undefined value.
Validate that all specified keys are present and non-empty in ENV.
52 53 54 55 |
# File 'lib/philiprehberger/env_loader.rb', line 52 def self.validate!(*keys) missing = keys.map(&:to_s).select { |key| ENV[key].nil? || ENV[key].empty? } raise ValidationError, "missing required keys: #{missing.join(', ')}" unless missing.empty? end |