Module: Nvar

Defined in:
lib/nvar.rb,
lib/nvar/engine.rb,
lib/nvar/version.rb,
lib/nvar/environment_variable.rb

Overview

Centralized configuration for required environment variables in your Ruby app.

Defined Under Namespace

Classes: Engine, EnvironmentVariable, EnvironmentVariableNotPresentError, Error

Constant Summary collapse

ENV_COMMENT =

Comments in .env files must have a leading ‘#’ symbol. This cannot be followed by a space.

<<~COMMENT
  #Environment variables are managed through this file (.env). The Scripts to
  #Rule Them All (in script/) load the environment from here, and the app warns
  #on startup if any required environment variables are missing. You can see the
  #list of environment variables that can be set for the app in
  #config/environment_variables.yml.
COMMENT
VERSION =
"0.2.0"

Class Method Summary collapse

Class Method Details

.allObject



63
64
65
66
67
68
# File 'lib/nvar.rb', line 63

def all
  variables.map do |variable_name, config|
    # TODO: Passthrough from environment behaviour might need to go here?
    EnvironmentVariable.new(**(config || {}).merge(name: variable_name))
  end.partition(&:set?)
end

.configure_for_rails(app) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/nvar.rb', line 41

def configure_for_rails(app)
  self.config_file_path = app.root.join("config/environment_variables.yml")
  self.env_file_path = app.root.join(".env")
  [config_file_path, env_file_path].each do |path|
    File.open(path, "w") {} unless path.exist? # rubocop:disable Lint/EmptyBlock
  end
end

.filter_from_vcr_cassettes(config) ⇒ Object



56
57
58
59
60
61
# File 'lib/nvar.rb', line 56

def filter_from_vcr_cassettes(config)
  set, = all
  set.reduce(config) do |c, env_var|
    c.tap { env_var.filter_from_vcr_cassettes(c) }
  end
end

.load_allObject



49
50
51
52
53
54
# File 'lib/nvar.rb', line 49

def load_all
  all.tap do |set, unset|
    set.map(&:to_const)
    raise EnvironmentVariableNotPresentError.new(*unset) if unset.any?
  end
end

.touch_envObject



70
71
72
# File 'lib/nvar.rb', line 70

def touch_env
  File.write(env_file_path, ENV_COMMENT, mode: "w") unless File.exist?(env_file_path)
end

.verify_env(write_to_file: true) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/nvar.rb', line 74

def verify_env(write_to_file: true)
  _set, unset = all
  return true if all_required_env_variables_set?

  puts "Please update .env with values for each environment variable:"
  touch_env if write_to_file
  unset.each do |variable|
    variable.add_to_env_file if write_to_file
    puts "- #{variable.name}"
  end
  puts "#{config_file_path} contains information on required environment variables across the app."
  # Don't exit if all unset variables had defaults that were written to .env
  write_to_file && unset.all? { |variable| variable.value.present? }
end