Class: Mitwelt

Inherits:
Object
  • Object
show all
Defined in:
lib/mitwelt.rb,
lib/mitwelt/version.rb

Defined Under Namespace

Modules: Types Classes: Error

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, type:, default:, required:) ⇒ Mitwelt

Returns a new instance of Mitwelt.



17
18
19
20
21
22
# File 'lib/mitwelt.rb', line 17

def initialize(key, type:, default:, required:)
  @key = key
  @type = type
  @default = default.freeze
  @required = required
end

Class Method Details

.fetch(key, type: :string, default: nil, required: false) ⇒ Object



13
14
15
# File 'lib/mitwelt.rb', line 13

def self.fetch(key, type: :string, default: nil, required: false)
  new(key, type: type, default: default, required: required).fetch
end

Instance Method Details

#fetchObject

Raises:



24
25
26
27
28
# File 'lib/mitwelt.rb', line 24

def fetch
  value = parsed_value
  raise(Error.new("#{@key} is required but not in ENV")) if @required && value.nil?
  value
end

#parsed_valueObject



30
31
32
33
34
# File 'lib/mitwelt.rb', line 30

def parsed_value
  parser[value]
rescue Dry::Types::CoercionError => error
  raise Error.new "Unable to parse #{@key} from ENV as #{@type}: #{error.message}"
end

#parserObject



36
37
38
39
40
41
42
43
44
45
# File 'lib/mitwelt.rb', line 36

def parser
  {
    string: Types::Coercible::String,
    symbol: Types::Coercible::Symbol,
    integer: Types::Params::Integer,
    boolean: Types::Params::Bool,
    timestamp: Types::Params::Time,
    date: Types::Params::Date
  }[@type].optional
end

#valueObject



47
48
49
# File 'lib/mitwelt.rb', line 47

def value
  ENV[@key].nil? ? @default : ENV[@key]
end