Skip to content

Commit

Permalink
Support default value for optional environment variables
Browse files Browse the repository at this point in the history
Prius helps us ensure that our application always boots with the
required state. However in large applications with multiple contributors,
this can cause a configuration error in an unrelated component to break
the entire application.

Providing a default value allows contributors to safely introduce new
configuration without worrying if the application breaks. For example:
```ruby
Prius.get(:my_worker_pool, type: int, required: false, default: 0)
```

It also means that boolean flags that are optional can be made to have a
default value of `false` rather than `nil`.

Note: This change _does not_ allow you to specify a default value for
required config, for obvious reasons.
  • Loading branch information
ameykusurkar committed Jul 12, 2024
1 parent d88c117 commit aca021f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
1 change: 1 addition & 0 deletions lib/prius/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ module Prius
class MissingValueError < StandardError; end
class TypeMismatchError < StandardError; end
class UndeclaredNameError < StandardError; end
class InvalidLoadError < StandardError; end
end
13 changes: 9 additions & 4 deletions lib/prius/registry.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,14 @@ def initialize(env)
end

# See Prius.load for documentation.
def load(name, env_var: nil, type: :string, required: true)
def load(name, env_var: nil, type: :string, required: true, default: nil)
env_var = name.to_s.upcase if env_var.nil?
value = load_value(env_var, required)

if required && !default.nil?
raise InvalidLoadError, "required config value #{env_var} cannot have default value"
end

value = load_value(env_var, required, default)
@registry[name] = case type
when :string then value
when :int then parse_int(env_var, value)
Expand All @@ -36,10 +41,10 @@ def get(name)

private

def load_value(name, required)
def load_value(name, required, default)
@env.fetch(name)
rescue KeyError
return nil unless required
return default unless required

raise MissingValueError, "config value '#{name}' not present"
end
Expand Down

0 comments on commit aca021f

Please sign in to comment.