Class: ASCM::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/ascm/reader.rb

Overview

Reader represents the base class that configuration classes should inherit in order to read settings from ENV

Constant Summary collapse

@@prefix =
nil

Class Method Summary collapse

Class Method Details

.def_setting(name, opts = {}) ⇒ Object

Public: Declares a new setting to be loaded from the local environment. It automatically appends the provided prefix (through #uses_prefix!) to the provided string and capitalizes it.

name - Name of the setting to be loaded opts - Hash of extra options.

default: used to automatically set a value when it cannot be found
         on the current environment. Defaults to `nil`.
map: Lambda to be called in order to map a value obtained from the
     environment. Won't be called when using a value supplied by
     the `default` key, and will fallback to the `default` value
     in case the Lambda throws an error.

Returns nothing, but defines two new methods on the inheriting class. Methods are based on the provided name. Defines a class method with the provided name and another method named ‘has_#name?`, that returns true whenever the value of #name is not nil. After loading settings, those cannot be changed dynamically during runtime.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/ascm/reader.rb', line 27

def self.def_setting(name, opts = {})
  string_name = name.to_s.freeze
  env_name = "#{@@prefix.nil? ? '' : "#{@@prefix}_"}#{string_name}".upcase
  default = opts.fetch(:default, nil)
  value = ENV.fetch(env_name, default)

  if opts.key? :map
    begin
      value = opts[:map][value]
    rescue StandardError => ex
      ASCM.logger.error("BaseConfig failed to map key #{name}:")
      ASCM.logger.error(ex)
      ASCM.logger.error("Falling back to default value '#{default}'")
      value = default
    end
  end

  define_singleton_method name do
    value
  end

  define_singleton_method "has_#{name}?" do
    !value.nil?
  end

  if string_name.start_with?('is_')
    define_singleton_method "#{name}?" do
      value
    end
  end
end

.uses_prefix!(prefix) ⇒ Object

Public: Marks the current configuration as to having a prefix before the declared names on #def_setting Reffer to #def_setting for further details.

prefix - Prefix used by the configuration keys

Returns nothing



66
67
68
# File 'lib/ascm/reader.rb', line 66

def self.uses_prefix!(prefix)
  @@prefix = prefix
end