Class: ConfigurableFromEnv::EnvironmentValue
- Inherits:
-
Object
- Object
- ConfigurableFromEnv::EnvironmentValue
- Defined in:
- lib/configurable_from_env/environment_value.rb
Constant Summary collapse
- TYPES =
%i[boolean integer string].freeze
- BOOLEAN_VALUES =
{}.merge( %w[1 true yes t y enable enabled on].to_h { [_1, true] }, %w[0 false no f n disable disabled off].to_h { [_1, false] }, { "" => false } ).freeze
Instance Attribute Summary collapse
-
#key ⇒ Object
readonly
Returns the value of attribute key.
-
#type ⇒ Object
readonly
Returns the value of attribute type.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(key:, type: :string, env: ENV) ⇒ EnvironmentValue
constructor
A new instance of EnvironmentValue.
- #read(required: true) ⇒ Object
Constructor Details
#initialize(key:, type: :string, env: ENV) ⇒ EnvironmentValue
Returns a new instance of EnvironmentValue.
21 22 23 24 25 26 27 28 29 |
# File 'lib/configurable_from_env/environment_value.rb', line 21 def initialize(key:, type: :string, env: ENV) unless TYPES.include?(type) raise ArgumentError, "Invalid type: #{type.inspect} (must be one of #{TYPES.map(&:inspect).join(', ')})" end @key = key @type = type @env = env end |
Instance Attribute Details
#key ⇒ Object (readonly)
Returns the value of attribute key.
19 20 21 |
# File 'lib/configurable_from_env/environment_value.rb', line 19 def key @key end |
#type ⇒ Object (readonly)
Returns the value of attribute type.
19 20 21 |
# File 'lib/configurable_from_env/environment_value.rb', line 19 def type @type end |
Class Method Details
.from(definition) ⇒ Object
11 12 13 14 15 16 17 |
# File 'lib/configurable_from_env/environment_value.rb', line 11 def self.from(definition) return nil if definition.nil? definition = { key: definition } unless definition.is_a?(Hash) definition.assert_valid_keys(:key, :type) new(**definition) end |
Instance Method Details
#read(required: true) ⇒ Object
31 32 33 34 35 36 37 38 |
# File 'lib/configurable_from_env/environment_value.rb', line 31 def read(required: true) if env.key?(key) value = convert(env[key]) block_given? ? yield(value) : value elsif required raise ArgumentError, "Missing required environment variable: #{key}" end end |