Module: Kernel

Defined in:
lib/early.rb

Class Method Summary collapse

Class Method Details

.Early(*envs, &block) ⇒ Object

Early checks for environment variables availability. It provides a DSL that can require or set a default value for an environment variable. This will help you catch configuration errors earlier in your application runtime. Here is an example:

Early do require :REDIS_URL default :PROVIDER, :generic end

Calling require :REDIS_URL will fail if ENV['REDIS_URL'] is nil, which means that it wasn’t provided, before running the current application. The error will give you information about the missing variable:

Early::Error (Variable ENV["REDIS_URL"] is missing)

Setting a default calls ENV['PROVIDER'] ||= 'generic' under the hood. Every time you use ENV['PROVIDER'] will give you 'generic'. No need to set it explicitly prior to the application run.

A quick note about how ENV works in Ruby. It is a plain Object that is monkey patched to behave a bit like a hash. You can get a variable with ENV['NAME'] and you can set a variable with ENV['NAME'] = 'val'.

Both of the operations explicitly require strings for the variable name and value. Passing a symbol to ENV[:NAME] will result in an error. The same will happen if you try to set a variable to any non-string value, like ENV['NAME'] = :val. Early converts both the name and the value to strings when it eventually deals with ENV, so you don’t have to worry about it.


129
130
131
132
133
134
# File 'lib/early.rb', line 129

def Early(*envs, &block)
  config = Early::Configuration.new(&block)
  if envs.empty? || envs.find { |e| Early.env == e.to_s }
    Early.apply(config)
  end
end