Module: Ace::Core::Atoms::EnvParser
- Defined in:
- lib/ace/core/atoms/env_parser.rb
Overview
Pure .env file parsing functions
Class Method Summary collapse
-
.format(env_hash) ⇒ String
Format hash as .env content.
-
.parse(content) ⇒ Hash
Parse .env file content into hash.
-
.unquote(value) ⇒ String
Remove quotes from value if present.
-
.valid_key?(name) ⇒ Boolean
Validate environment variable name.
Class Method Details
.format(env_hash) ⇒ String
Format hash as .env content
41 42 43 44 45 46 47 48 |
# File 'lib/ace/core/atoms/env_parser.rb', line 41 def format(env_hash) return "" if env_hash.nil? || env_hash.empty? env_hash.map do |key, value| formatted_value = value.to_s.include?(" ") ? %("#{value}") : value.to_s "#{key}=#{formatted_value}" end.join("\n") end |
.parse(content) ⇒ Hash
Parse .env file content into hash
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/ace/core/atoms/env_parser.rb', line 13 def parse(content) return {} if content.nil? || content.strip.empty? result = {} lines = content.lines.map(&:strip) lines.each do |line| # Skip empty lines and comments next if line.empty? || line.start_with?("#") # Parse KEY=VALUE format if (match = line.match(/\A([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\z/)) key = match[1] value = match[2] # Handle quoted values value = unquote(value) result[key] = value end end result end |
.unquote(value) ⇒ String
Remove quotes from value if present
60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/ace/core/atoms/env_parser.rb', line 60 def unquote(value) return value unless value.is_a?(String) # Handle double quotes if value.start_with?('"') && value.end_with?('"') value[1..-2].gsub('\\"', '"').gsub("\\n", "\n").gsub("\\\\", "\\") # Handle single quotes elsif value.start_with?("'") && value.end_with?("'") value[1..-2] else value end end |
.valid_key?(name) ⇒ Boolean
Validate environment variable name
53 54 55 |
# File 'lib/ace/core/atoms/env_parser.rb', line 53 def valid_key?(name) !name.nil? && name.match?(/\A[A-Za-z_][A-Za-z0-9_]*\z/) end |