Class: Foruiman::Env

Inherits:
Object
  • Object
show all
Defined in:
lib/foruiman/env.rb

Overview

Foreman's assignment and quoting rules, with a non-mutating merge API.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename) ⇒ Env

Returns a new instance of Env.



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/foruiman/env.rb', line 5

def initialize(filename)
  @entries = File.read(filename).gsub("\r\n", "\n").split("\n").each_with_object({}) do |line, result|
    next unless (match = line.match(/\A([A-Za-z_0-9]+)=(.*)\z/))

    key, value = match.captures
    result[key] = case value
                  when /\A'(.*)'\z/ then Regexp.last_match(1)
                  when /\A"(.*)"\z/ then Regexp.last_match(1).gsub('\\n', "\n").gsub(/\\(.)/, '\1')
                  else value
                  end
  end
end

Class Method Details

.load(root: Dir.pwd, file: nil, dotenv: true, inherited: ENV.to_h) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/foruiman/env.rb', line 28

def self.load(root: Dir.pwd, file: nil, dotenv: true, inherited: ENV.to_h)
  env = inherited.dup
  default = File.join(root, ".env")
  if file
    Array(file).each { |filename| env.merge!(new(filename).to_h) }
  elsif dotenv && File.file?(default)
    env.merge!(new(default).to_h)
  end
  env.transform_values { |value| value.dup.freeze }.freeze
end

Instance Method Details

#entries(&block) ⇒ Object



18
19
20
21
22
# File 'lib/foruiman/env.rb', line 18

def entries(&block)
  return @entries.each unless block

  @entries.each(&block)
end

#to_h ⇒ Object



24
25
26
# File 'lib/foruiman/env.rb', line 24

def to_h
  @entries.dup
end