Class: Chambermaid::Environment

Inherits:
Hash
  • Object
show all
Defined in:
lib/chambermaid/environment.rb

Overview

Environment keeps a set of params available to load into ENV. It also maintains a copy of ENV at the time of its initialization, in order to restore it.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ Chambermaid::Environment

Create new Chambermaid::Environment

Parameters:

  • params (Hash)

Raises:

  • (ArgumentError)

    if params is not type Hash



18
19
20
21
22
# File 'lib/chambermaid/environment.rb', line 18

def initialize(params)
  validate_params!(params)
  stash_current_env!
  update(format_env(params))
end

Instance Attribute Details

#paramsHash (readonly)

Returns the current value of params.

Returns:

  • (Hash)

    the current value of params



7
8
9
# File 'lib/chambermaid/environment.rb', line 7

def params
  @params
end

Instance Method Details

#load!Hash

Inject into ENV without overwriting duplicates

Returns:

  • (Hash)


45
46
47
# File 'lib/chambermaid/environment.rb', line 45

def load!
  each { |k, v| ENV[k] ||= v }
end

#overload!Hash

Inject into ENV and overwrite duplicates

Returns:

  • (Hash)


52
53
54
# File 'lib/chambermaid/environment.rb', line 52

def overload!
  each { |k, v| ENV[k] = v }
end

#to_dotenvString

Generate a dotenv (.env) compatible string

Returns:

  • (String)

    dotenv compatible string



27
28
29
30
31
# File 'lib/chambermaid/environment.rb', line 27

def to_dotenv
  to_h.inject("") do |env_str, param|
    env_str + "#{param[0]}=#{param[1]}\n"
  end
end

#to_file!(file_path) ⇒ Object

Write a .env file

Parameters:

  • file_path (String)


36
37
38
39
40
# File 'lib/chambermaid/environment.rb', line 36

def to_file!(file_path)
  File.open(file_path, "wb") do |f|
    f.write(to_dotenv)
  end
end

#unload!ENV

Restore to original ENV

Returns:

  • (ENV)


59
60
61
# File 'lib/chambermaid/environment.rb', line 59

def unload!
  ENV.replace(@_original_env)
end